可能重复:
python, basic question on loops
how to let a raw_input repeat until I wanna quit?
我想要一些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之后,程序会自动退出。有没有办法可以让程序重新启动,以便再次询问它们“你想做什么?”;这样就会继续发生,直到用户退出程序。
答案 0 :(得分: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.")
答案 1 :(得分: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)")
答案 2 :(得分: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.")
答案 3 :(得分:0)
我个人建议你这样做。我会把它放到一个while循环中,main是你的程序然后它在第一个循环完成后运行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