python 2.7.3 while循环

时间:2013-04-03 02:13:43

标签: python

我对python很新。我需要反复循环,要求用户选择一个选项,然后运行命令并重复直到用户选择退出。如果用户选择任何其他选项,程序必须一直要求他们选择一个值,直到他们选择一个正确的值。到目前为止,我的计划进展不顺利。如果可能的话,我想保持原状,如果,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"

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

这就是我如何修改它以达到预期的结果。你在哪里关闭但是if和else不应该在循环中:)。

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 >3:
    print "Please try again"
    option = input("Please select one of the above options: ")

if option == 1:
    print "happy"
elif option == 2:
    print "average"
elif option == 3:
    print "sad"
else:
    print "done"

请注意,您可以随时使用break来停止循环

由于 本

答案 2 :(得分:1)

import sys
option = int(input("Please select one of the above options: "))
while not option in (0, 1, 2, 3):
    option = int(input("Please select one of the above options: ")
    if option == 0: sys.exit()
    else: print "Please try again"
if option == 1:
        print "happy"
elif option == 2:
        print "average"
elif option == 3:
        print "sad"

逻辑是如果选项不是0,1,2或3,程序会不断要求输入。如果它在该范围内,则循环结束并打印结果。如果输入为0,则程序以sys.exit()结束。

或者,您可以使用dictionary创建更简单,更短的程序:

import sys
userOptions = {1: 'happy', 2: 'average', 3: 'sad'}
option = int(input("Please select one of the above options: "))
while not option in (0, 1, 2, 3):
    option = int(input("Please select one of the above options: ")
    if option == 0: sys.exit()
    else: print "Please try again"
print userOptions[option]