2012-03-24 77 views
1

可能重复:
python, basic question on loops
how to let a raw_input repeat until I wanna quit?的Python - 循环的输入

我想一些帮助的Python请。

我在Py2.7.2中编写程序,但遇到一些问题。

我有什么到目前为止是这样的:

choice = raw_input("What would you like to do") 
if choice == '1': 
    print("You chose 1") 
elif choice == '2': 
    print("You chose 2") 
elif choice == '3': 
    print("You chose 3") 
else: 
    print("That is not a valid input.") 

但用户选择是1,2,3或4后,程序会自动退出。有没有一种方法可以让程序循环备份,以便再次询问他们“您想要做什么?”;并且这样继续发生,直到用户退出程序。

回答

4

你可以用while循环完成。这里更多的信息: http://wiki.python.org/moin/WhileLoop

示例代码:

choice = "" 

while choice != "exit": 
    choice = raw_input("What would you like to do") 
    if choice == '1': 
     print("You chose 1") 
    elif choice == '2': 
     print("You chose 2") 
    elif choice == '3': 
     print("You chose 3") 
    else: 
     print("That is not a valid input.") 
0

你需要一个循环:

while True: 
    choice = raw_input("What would you like to do") 
    if choice == '1': 
     print("You chose 1") 
    elif choice == '2': 
    print("You chose 2") 
    elif choice == '3': 
    print("You chose 3") 
    else: 
    print("That is not a valid input.") 
2

使用While Loop -

choice = raw_input("What would you like to do (press q to quit)") 

while choice != 'q': 
    if choice == '1': 
     print("You chose 1") 
    elif choice == '2': 
     print("You chose 2") 
    elif choice == '3': 
     print("You chose 3") 
    else: 
     print("That is not a valid input.") 
    choice = raw_input("What would you like to do (press q to quit)") 
0

个人这是怎么了,我建议你做吧。我会把它放到一个while循环中,主要是你的程序,然后在第一个循环完成后运行exit语句。这是一种更干净的方式来做事情,因为您可以编辑选择,而不必担心必须编辑退出代码。 :)

def main(): 
    choice=str(raw_input('What would you like to do?')) 
    if choice == '1': 
     print("You chose 1") 
    elif choice == '2': 
     print("You chose 2") 
    elif choice == '3': 
     print("You chose 3") 
    else: 
     print("That is not a valid input.") 
if __name__=='__main__': 
    choice2="" 
    while choice2 != 'quit': 
     main() 
     choice2=str(raw_input('Would you like to exit?: ')) 
     if choice2=='y' or choice2=='ye' or choice2=='yes': 
      choice2='quit' 
     elif choice2== 'n' or choice2=='no': 
      pass