繁体   English   中英

python 2.7.3 while循环

[英]python 2.7.3 while loop

我是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"

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

这是我将如何修改它以实现预期的结果。你在哪里关闭但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来停止循环

谢谢Ben

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM