Python - Looping an Input [duplicate]

不羁岁月 提交于 2020-04-30 07:28:11

问题


Possible Duplicate:
python, basic question on loops
how to let a raw_input repeat until I wanna quit?

I would like some help with Python please.

I'm writing a program in Py2.7.2, but am having some issues.

What I have so far is something like this:

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.")

But after the user chooses either 1, 2, 3 or 4, the program automatically exits. Is there a way that I can loop the program back up so that it asks them again "What would you like to do?"; and so that this continues to happen, until the user exits the program.


回答1:


You can accomplish that with a while loop. More info here: http://wiki.python.org/moin/WhileLoop

Example code:

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.")



回答2:


Use a 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)")



回答3:


You need a loop:

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.")



回答4:


Personally this is how i would suggest you do it. I would put it into a while loop with the main being your program then it runs the exit statement after the first loop is done. This is a much cleaner way to do things as you can edit the choices without having to worry about the exit code having to be edited. :)

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


来源:https://stackoverflow.com/questions/9849281/python-looping-an-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!