为什么我的程序将int添加为字符串(4 + 7 = 47)?

时间:2015-06-05 01:21:18

标签: python python-2.7

import time


print "1.Addition"
print "2.Subtraction"
print "3.Multiplication"
print "4.Division\n"

numChoice = int(raw_input("Type the number corresponding to the subject of arithmetic you would like to work with: "))

print "Loading..."

time.sleep(2)
if numChoice==1:
    print "\nYou have chosen Addition!"
    num1Add = int(raw_input("Please enter your first number:"))
    num2Add = int(raw_input("Please enter your second number:"))
    numAddRes = num1Add+num2Add
    print "Calculating..."
    time.sleep(2)
    print num1Add+" plus "+num2Add+" is equal to: "+num2Add+num1Add

不确定为什么它会像它一样添加,我尝试了int()的东西,但它不起作用。 因此,每当我输入我的数字并且它吐出结果时,它会以奇怪的方式添加它,例如10 + 10 = 1010

1 个答案:

答案 0 :(得分:0)

计算机从左到右逐位评估该表达式,如下所示:

print num1Add+" plus "+num2Add+" is equal to: "+num2Add+num1Add
print "4 plus "+num2Add+" is equal to: "+num2Add+num1Add
print "4 plus 7"+" is equal to: "+num2Add+num1Add
print "4 plus 7 is equal to: "+num2Add+num1Add
print "4 plus 7 is equal to: 4"+num1Add
print "4 plus 7 is equal to: 47"

看到它在最后一步中为一个字符串添加了7。因此,请务必先进行整数加法(在该部分周围添加括号):

print num1Add+" plus "+num2Add+" is equal to: "+(num2Add+num1Add)

或者,也可以使用您的numAddRes变量:

print num1Add+" plus "+num2Add+" is equal to: "+numAddRes
编辑:我测试了这个,以确保我不是疯了(我实际上不是一个python用户,但幸运的是,我的机器有python):

>>> num1 = int(raw_input("Enter a number: "))
Enter a number: 1
>>> type(num1)
<type 'int'>
>>> num2 = int(raw_input("Enter a number: "))
Enter a number: 4
>>> type(num2)
<type 'int'>
>>> res = num1 + num2
>>> type(res)
<type 'int'>
>>> res
5

你可以看到它按预期工作!

EDIT2:好的,结果是python需要显式类型转换才能连接整数和字符串。所以我不确定,但也许你没有给出完整的代码?我希望你能看到类似的错误。

>>> "result: " + num1 + num2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> "result: " + (num1 + num2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> "result: " + str(num1 + num2)
'result: 5'