我是python的新手并试图编写一个程序,要求用户猜测一个数字,1 - 6然后他们被告知他们是否猜对了。但是,即使用户猜对了,仍然会返回else语句。
我为初学者问题道歉,虽然这确实让我卡住了,因为'guess'变量被正确分配了,我通过在函数外部移动print("Your guess was: ",guess)
来测试这个并在调用函数后执行始终返回的值与用户输入的值相同。
#Function to take guess
def userGuess (guess):
guess = input("Take a guess.\n")
print("Your guess was: ",guess)
return guess
#Define Variables
diceNum = random.randint(1,6)
guess = 0
#Call Function
guess = userGuess(guess)
#Check answer
if guess == diceNum:
print("You guessed right!, the number was: ",diceNum)
else:
print("You did not guess it right, the number was: ",diceNum)
答案 0 :(得分:2)
在比较之前,您需要将用户输入转换为整数:
guess = int(input("Take a guess.\n"))
如果您想要解释为什么 if语句返回false
以进行整数和字符串之间的比较,请查看this question。