1

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

  • How old is the tutorial? This will work in Python 2.x, but not Python 3.x. – Barmar Nov 05 '20 at 17:39
  • Hello! "Isn't working and I don't know why" isn't a great way to ask for help. What do you mean by "isn't working"? What does it do? What do you expect it to do? Any errors? Have you tried any debugging? [How to debug small programs.](//ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Pranav Hosangadi Nov 05 '20 at 17:40
  • 1
    Does this answer your question? [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) – G. Anderson Nov 05 '20 at 17:56

2 Answers2

4

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

c = int(a) + int(b)

Suggested read:

Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
0

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.

tdelaney
  • 73,364
  • 6
  • 83
  • 116