Why is my program adding int as string (4+7 = 47)?

57 views Asked by At
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

Not sure why it keeps adding like it does, I tried the int() stuff, but it doesn't work. So whenever I input my numbers and it spits out the result, it will add it in a weird way, like 10+10 = 1010

1

There are 1 answers

1
Luke On

The computer evaluates that expression bit by bit, left to right, as follows:

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"

See that it adds 7 to a string in that last step. So, make sure to do the integer addition first (add parenthesis around that part):

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

Or, alternatively, make use of your numAddRes variable:

print num1Add+" plus "+num2Add+" is equal to: "+numAddRes

EDIT: I tested this to make sure I'm not insane (I'm not actually a python user, but luckily, my machine has 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

You can see that's working as expected!


EDIT2: Okay, turns out python needs explicit type casting for the concatenation of ints and strings. So I'm not sure, but perhaps you haven't given the full code? I'd expect you to be seeing similar type errors.

>>> "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'