2012-03-24 76 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