将int添加为字符串不会输出正确的值

时间:2014-11-18 23:58:22

标签: python

import time
import random
print("Hi user, what is your name?")
name = input()
print("Right "+name," lets get on!")
time.sleep(1)
number1 = random.randrange(1, 50)
number2 = random.randrange(1, 50)
print("What is " + str(number1) + "+" + str(number2))
response = input()
answer = str(number1) + str(number2)
if response == answer:
    print("Welldone " + name + "That's Right!")
elif response != answer:
    print("I'm afraid that's wrong, maybe next time!") 

即使答案是正确的,它也会输出:"我担心错了,也许是下次!"

2 个答案:

答案 0 :(得分:2)

当您执行str(number1) + str(number2)时,您将两个字符串一起添加,因此您获得了"25" + "30",它会为您提供"2530"。您希望在添加数字后转换为字符串

str(number1 + number2)

当您遇到这样的问题时,您知道if的子句response == answer必须返回False。要进行调试,请尝试打印出相等的两面并检查它们 - 它会使这样的错误非常明显。

答案 1 :(得分:0)

在教导人对鱼方面,让我们来看看问题:

if response == answer:
    print("Welldone " + name + "That's Right!")
elif response != answer:
    print("I'm afraid that's wrong, maybe next time!") 

显然认为答案和答案应该是平等的,而计算机则说它们不是。嗯,有什么价值?要么"回复"不是你的想法(例如,它有空格或换行符),或者"回答"不是你的想法(例如,它是" 2530"而不是" 55"),或两者兼而有之。

如果你添加

print response, answer
在if语句之前,你可能会实现启蒙。