2014-12-06 53 views
-1

我對如何讓用戶重試在Python中輸入內容有點困惑。我創建了一個示例代碼。我希望如此,如果用戶鍵入1或2以外的無效答案,則允許他們再次嘗試。你將如何創建一個在Python中重試的選項?

import sys 

def start(): 
    print "Hello whats your name?" 
    username = raw_input("> ") 
    print "Okay, welcome to the game %s" % username 
    print "Do you want to hear the background of the game?" 
    print "1. Yes" 
    print "2. No" 

    background = raw_input("> ") 

    if background == "1": 
      print "Background goes here." 

    elif background == "2": 
     print "Background skipped" 
start() 

我該如何將再次嘗試選項納入此示例?謝謝!

+1

你需要來包裝你想在一個循環中重複的代碼。然後,如果輸入是1或2,則跳出循環。 – 2014-12-06 05:35:11

+0

[詢問用戶輸入,直到他們給出有效響應](http://stackoverflow.com/questions/23294658/asking-the-user - 用於輸入,直到 - 他們放棄的一個有效響應) – jonrsharpe 2014-12-07 09:15:50

回答

1

使用while循環:

def start(): 
    print "Hello whats your name?" 
    username = raw_input("> ") 
    print "Okay, welcome to the game %s" % username 
    print "Do you want to hear the background of the game?" 
    print "1. Yes" 
    print "2. No" 
    while True:       # Repeat the following block of code infinitely 
     background = raw_input("> ") 

     if background == "1": 
      print "Background goes here." 
      break       # Break out of loop if we get valid input 
     elif background == "2": 
      print "Background skipped" 
      break       # Break out of loop if we get valid input 
     else: 
      print "Invalid input. Please enter either '1' or '2'" # From here, program jumps back to the beginning of the loop 

start() 
相關問題