Python - Looping an Input
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
python, basic question on loops
how to let a raw_input repeat until I wanna quit?
我想要一些Python的帮助。
我在Py2.7.2中编写了一个程序,但是我遇到了一些问题。
到目前为止我所拥有的是这样的:
1 2 3 4 5 6 7 8 9 | 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之后,程序会自动退出。 有没有办法可以让程序重新启动,以便再次询问它们"你想做什么?"; 这样就会继续发生,直到用户退出程序。
你可以用while循环完成它。 更多信息:
http://wiki.python.org/moin/WhileLoop
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 | 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.") |
使用While循环 -
1 2 3 4 5 6 7 8 9 10 11 12 | 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)") |
就个人而言,这就是我建议你这样做的方式。 我会把它放到一个while循环中,main是你的程序然后它在第一个循环完成后运行exit语句。 这是一种更简洁的方法,因为您可以编辑选项而无需担心必须编辑退出代码。:)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 |
你需要一个循环:
1 2 3 4 5 6 7 8 9 10 | 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.") |