-2

所以,我一直在制作一个基于文本的冒险游戏,它会询问你的年龄。如果您的年龄小于 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.")
4

3 回答 3

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)

这将反复询问您的年龄,直到您最终给它一个数字,此时它将跳出循环。

于 2013-10-19T09:01:07.433 回答
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.")
于 2013-10-19T09:44:10.490 回答
-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")
于 2013-10-19T09:17:19.770 回答