4

我对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"
4

3 回答 3

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
于 2013-04-03T02:18:17.257 回答
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 来停止循环

谢谢本

于 2013-04-03T02:26:51.927 回答
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()

或者,您可以使用字典来创建更简单、更短的程序:

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]
于 2013-04-03T02:17:03.610 回答