简体   繁体   中英

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

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

c = int(a) + int(b)

Suggested read:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM