trackvis skots
trackvis skots

Reputation: 21

My simple addition code isn't working and I don't know why

I'm new and I'm trying math in python but i ran into an issue. Let's say a=10 and b=20 so a+b=30. But when I run the code i get 1020 instead. I got a tutorial, followed it, but it still doesn't work.

a = input('what is a?')
b = input('what is b?')
c = 0

c = a + b
print ('answer is', c)

I'm on python 3.9

Upvotes: 1

Views: 150

Answers (2)

tdelaney
tdelaney

Reputation: 77337

Python lets you experiment. Python is a dynamic language and objects can implement things like "+" in different ways. You can use the shell to see how it works.

>>> a = input('what is a?')
what is a?10
>>> b = input('what is b?')
what is b?20
>>> type(a)
<class 'str'>
>>> type(b)
<class 'str'>
>>> a + b
'1020'

So, a and b are strings and + for strings concatentates. Lets make some integers.

>>> aa = int(a)
>>> bb = int(b)
>>> type(aa)
<class 'int'>
>>> type(bb)
<class 'int'>
>>> aa+bb
30

That's more like it. Integers add like you think they should.

BTW c = 0 isn't needed. Its just reassigned later anyway.

Upvotes: 0

Chankey Pathak
Chankey Pathak

Reputation: 21666

The input from STDIN is string (str), you need to convert that to integer (int).

c = int(a) + int(b)

Suggested read:

Upvotes: 4

Related Questions