2013-11-14 37 views
2

只需要一点帮助。开始做python,试图创建一个高分程序,我想说的是,分数不等于一个整数,然后要求用户输入分数。Python:检查变量是否为int(使用while循环)

例如(这不起作用)

name = input("Please enter your name: ") 
score = None 
while score != int(score): 
    score = input("Enter your score: ") 
print("congratz it worked genius") 

在此先感谢

+0

可能重复:http://stackoverflow.com/questions/5424716/python-how-to- check-if-input-is-a-number-given-that-input-always-returns-stri –

+0

1.你的分数仍然是一个字符串,所以它永远不能等于一个整数,所以你永远不会离开你的循环。 2. int(score)会为任何不包含整数的字符串引发ValueError,因此您的错误输入将导致异常。查尼古拉斯的回答。 – SzieberthAdam

回答

4
while True: 
    try: 
     score = int(input("Enter your score: ")) 
     break 
    except ValueError: 
     print("Int, please.") 
+0

为什么问题代码无法识别输入,即使它是一个int? –