我对如何允许用户重新在Python中输入内容感到困惑。我在下面创建了一个示例代码。我希望如此,如果用户输入1或2以外的无效答案,则允许他们再试一次。
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()
如何在此示例中加入try again选项?谢谢!
答案 0 :(得分: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()