2013-04-03 52 views
4

我对python很陌生。我需要重复循环,要求用户选择一个选项,然后运行命令并重复直到用户选择退出。如果用户选择其他选项,程序必须不断要求他们选择一个值,直到他们选择一个正确的值。到目前为止,我的计划并不顺利。如果可能的话,我希望保持这种状态。有人能够帮助吗?非常感谢!python 2.7.3 while循环

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" 
+0

停止循环使用'input'在Python 2是关于安全方面有不好的想法。使用'raw_input'并将结果转换为一个'int'(或者只是使用字符串)。 – Matthias

回答

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] 
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

“while-true-break”模式在Python中很常见。这并没有什么特别的不利因素 - 它只是在循环终止时发生的意图 - 无论是在条件检查还是在循环运行期间。 – Makoto

+0

@Makoto我非常同意 - 但同时,在编程的早期阶段阻止过度使用'break'是相当标准的,以帮助加强对控制流和不同方法的理解(不能简单地例如,从嵌套循环中断开)。不过,这只是我的看法。 –

2

这是我怎么会修改以达到预期的result.You其中接近,但如果和别人的不应该是循环:)内。

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随时

感谢 本