我对python很陌生。我需要反复循环,要求用户选择一个选项,然后运行命令并重复直到用户选择退出。如果用户选择任何其他选项,程序必须不断要求他们选择一个值,直到他们选择正确的值。到目前为止,我的程序还没有那么顺利。如果可能的话,我想保持 while,if,elif 条件。有人可以提供帮助吗?非常感谢!
print """
How do you feel today?
1 = happy
2 = average
3 = sad
0 = exit program
"""
option = input("Please select one of the above options: ")
while option > 0 or option <=3:
if option > 3:
print "Please try again"
elif option == 1:
print "happy"
elif option == 2:
print "average"
elif option == 3:
print "sad"
else:
print "done"
最佳答案
break
命令将为您退出循环 - 但是,就开始控制流而言,也不推荐这样做。但是请注意,用户永远不能输入新值,因此您将陷入无限循环。
也许试试这个:
running = True
while running:
option = input("Please select one of the above options: ")
if option > 3:
print "Please try again"
elif option == 1:
print "happy"
elif option == 2:
print "average"
elif option == 3:
print "sad"
else:
print "done"
running = False
关于python 2.7.3 while 循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15777741/