简体   繁体   中英

need an explanation to the with AttributeError 'int' object has no attribute error in my code

Problem with adding integers

tried setting the number to a list and adding the index values but they did not ad even though they were previously defined as an integer

number=int(input("What is your number ?"))
print(number[0]+number[1]+number[2])

I think number is a string, if you do input("What is your number ?") and if you use whitespace, it should look like:

number = "1 2 3"

If you need to sum these numbers, you simply do:

sum(int(x) for x in number.split())

Probably easier to do that indexing on a string. You cannot index an int in Python as a list.

number = str(input("What is your number ?"))
print(int(number[0]) + int(number[1]) + int(number[2]))

Sample run:

What is your number ? 
543

output:

12

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