所以,我一直在制作基于文本的冒险游戏,它会询问你的年龄。如果你的年龄小于13岁则退出游戏,如果它更大或相等也可以让你玩。我现在要做的就是这样做,如果年龄不是一个数字,它会要求你租用年龄,所以有点重播剧本。
有没有办法做到这一点?
age = input()
if age >= 13:
print("You are old enough to play! Let's get started!")
elif age != int:
print("This is not a number")
(该语法不起作用,加上我希望它再次让您输入年龄进行验证。)
else:
print("You are not old enough.")
time.sleep(1)
sys.exit("Please exit the console, you are too young to play.")
答案 0 :(得分:2)
while True:
age = raw_input("Please enter your age > ")
try:
age = int(age)
except ValueError:
print "Please enter a number"
continue
else:
break
print "You age is {0}".format(age)
# Now do whatever you want with `age`
if age < 13:
print "You are not old enough to play the game!"
sys.exit(1)
这会反复询问你的年龄,直到你最后给它一个数字,此时它会突破循环。
答案 1 :(得分:0)
尝试以下代码
import sys
while True:
age = raw_input("Please enter your age > ")
try:
age = int(age)
except ValueError:
print "This is not a number"
else:
if age >= 13:
print("You are old enough to play! Let's get started!")
break
else:
print("You are not old enough.")
sys.exit("Exiting the console, you are too young to play.")
答案 2 :(得分:-2)
尝试:
#!/usr/bin/env python
import sys
try:
age = int(input("How old are you?"))
except ValueError:
print "Enter a valid number. (integer)."
else:
if age >= 13: # if age is more than 12
#run program
print "Game starting!" # code for game loop would start here
else:
print "You are too young!" # if less than 13 is entered, this is run
sys.exit("You must be 13 or above to play this game")