Rob Churan
Rob Churan

Reputation: 11

adding two variables that represent integers

I have been making an AI (in python 2.7.11) which can be used as a personal entertainment tool/calculator/whatever else and seem to have encountered a problem. I can't add two variables that I got from the raw_input function. instead of getting 19 in a test, I got 712. I'll give you some code in context to help:

mp=raw_input('do you want to add, subtract, multiply, divide, use exponents, or squareroot?:')

if mp=='add':

     numx=raw_input('what number for x in a problem x _ y?:')

     numy=raw_input('what number for y in a problem x _ y?:')

     print (numx+numy)

Upvotes: 0

Views: 120

Answers (2)

paxdiablo
paxdiablo

Reputation: 882566

The result of raw_input is a string so, if you add together the strings '7' and '12', you will indeed get '712'. This is string concatenation rather than numeric addition.

To get numeric addition, you need to turn them into numeric values before attempting to add them, and this can be done with something like:

try:
    intx = int(numx)
    inty = int(numy)
    print intx + inty
except ValueError:
    print 'One or both could not be converted'

The int() calls try to convert the string values into numeric values and then adds them together. The try...except code is simply to handle invalid input data.

Upvotes: 2

Ferit
Ferit

Reputation: 9727

Change this line, cast strings to int.

print (int(numx)+int(numy))

Upvotes: 0

Related Questions