我做了一个简单的猜数字程序,在我学习python的过程中!洛尔
然而,计算机不会确认用户的猜测是正确的,并且它总是会变为“不正确”,即使计算机编号显示为用户猜测。我的代码似乎是正确的,所以我不知所措。任何帮助表示赞赏!def randomNumGen():
userGuess = input('The Computer has thought of a number between 1-5, deposit your guess now!: ')
if finalValue == userGuess:
print("You've guessed correctly!, Very lucky you are!")
else:
print("You're guess was incorrect, try again please")
print("The computer's guess was",finalValue)
main()
编辑:
输出看起来像这样,这解释了这里显而易见的问题:
>The Computer has thought of a number between 1-5, deposit your guess now!: 2
>You're guess was was incorrect
>The computer's guess was 2
所以当'计算机'被给出时,它将无法识别正确的猜测。
答案 0 :(得分:3)
最有可能finalValue
是一个整数,而来自input()
的输入将是一个字符串。在比较之前,你应该把它们变成字符串,或者两者都变成整数。
要将整数转换为字符串,您只需执行以下操作:
my_string = str(my_integer)
这将采用名为my_integer
的整数并返回一个字符串,该字符串将被指定为my_string
def randomNumGen():
userGuess = input('The Computer has thought of a number between 1-5, deposit your guess now!: ')
if str(finalValue) == userGuess:
print("You've guessed correctly!, Very lucky you are!")
else:
print("You're guess was incorrect, try again please")
print("The computer's guess was",finalValue)
main()
这是我能看到的最简单的改变,可以使这项工作成功。注意这一行:
if str(finalValue) == userGuess:
我正在将finalValue
强制转换为与userGuess
的字符串进行比较。
答案 1 :(得分:0)
我认为问题在于,当需要将输入识别为整数时,您的输入将被处理为字符串。试试这个:
def randomNumGen():
userGuess = input('The Computer has thought of a number between 1-5, deposit your guess now!: ')
userGuess = int(userGuess)
if finalValue == userGuess:
print("You've guessed correctly!, Very lucky you are!")
else:
print("You're guess was incorrect, try again please")
print("The computer's guess was",finalValue)
main()