由于第6行,代码无法正常运行,但可以正常运行

时间:2020-01-07 18:15:01

标签: python-3.x

import random
randomNum=random.randint(1,9999)
print(randomNum)
userGuess=input("Please guess a 4 digit number, if you get it correct, we'll tell you, otherwise we will tell if you got any of the positions of the numbers correct\n")
if userGuess==randomNum:
    print("Congratulations, you guessed the number correctly")

为什么输入正确的数字后最后一行不起作用?我不认为它是缩进的,我很困惑。

2 个答案:

答案 0 :(得分:2)

您需要将userGuess强制转换为整数。 即

import random
randomNum=random.randint(1,9999)
print(randomNum)
userGuess=int(input("Please guess a 4 digit number, if you get it correct, we'll tell you, otherwise we will tell if you got any of the positions of the numbers correct\n"))
if userGuess==randomNum:
    print("Congratulations, you guessed the number correctly")

答案 1 :(得分:1)

默认情况下,输入被视为str,而不是输入值的数据类型,这就是为什么您需要接受输入并将其秘密转换为int或将randomNum转换为{ {1}}。

str

OR

import random
randomNum= str(random.randint(1,9999))
print(randomNum)
userGuess=input("Please guess a 4 digit number, if you get it correct, we'll tell you, otherwise we will tell if you got any of the positions of the numbers correct\n")
if userGuess==randomNum:
    print("Congratulations, you guessed the number correctly")