Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 'add' function issue: why won't this work?

I've just started studying Python, and I'm an absolute newbie.

I'm starting to learn about functions, and I wrote this simple script:

def add(a,b):   
    return a + b

print "The first number you want to add?"
a = raw_input("First no: ")
print "What's the second number you want to add?"
b = raw_input("Second no: ")

result = add(a, b)

print "The result is: %r." % result 

The script runs OK, but the result won't be a sum. I.e: if I enter 5 for 'a', and 6 for 'b', the result will not be '11', but 56. As in:

The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: '56'.

Any help would be appreciated.

like image 539
user2331291 Avatar asked Feb 15 '26 19:02

user2331291


1 Answers

raw_input returns string, you need to convert it to int

def add(a,b):   
    return a + b

print "The first number you want to add?"
a = int(raw_input("First no: "))
print "What's the second number you want to add?"
b = int(raw_input("Second no: "))

result = add(a, b)

print "The result is: %r." % result 

Output:

The first number you want to add?

First no: 5
What's the second number you want to add?

Second no: 6
The result is: 11.
like image 59
Kiro Avatar answered Feb 19 '26 19:02

Kiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!