Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'int' object is not subscriptable

I'm trying to create a simple program that tells you your lucky number according to numerology. I keep on getting this error:

File "number.py", line 12, in <module>     sumln = (int(sumall[0])+int(sumall[1])) TypeError: 'int' object is not subscriptable 

My script is:

birthday = raw_input("When is your birthday(mm/dd/yyyy)? ") summ = (int(birthday[0])+int(birthday[1])) sumd = (int(birthday[3])+int(birthday[4])) sumy= (int(birthday[6])+int(birthday[7])+int(birthday[8])+int(birthday[9])) sumall = summ + sumd + sumy print "The sum of your numbers is", sumall sumln = (int(sumall[0])+int(sumall[1])) print "Your lucky number is", sumln`    
like image 569
Cristal Isabel Avatar asked Jan 29 '12 16:01

Cristal Isabel


People also ask

How do I fix TypeError int object is not Subscriptable?

The TypeError: 'int' object is not subscriptable error occurs if we try to index or slice the integer as if it is a subscriptable object like list, dict, or string objects. The issue can be resolved by removing any indexing or slicing to access the values of the integer object.

What does object not Subscriptable mean?

Python throws the TypeError object is not subscriptable if you use indexing with the square bracket notation on an object that is not indexable. This is the case if the object doesn't define the __getitem__() method. You can fix it by removing the indexing call or defining the __getitem__ method.

Are tuples Subscriptable?

The objects that contain other objects or data types, like strings, lists, tuples, and dictionaries, are subscriptable.

Which object is Subscriptable?

In simple words, objects which can be subscripted are called sub scriptable objects. In Python, strings, lists, tuples, and dictionaries fall in subscriptable category.


2 Answers

The error is exactly what it says it is; you're trying to take sumall[0] when sumall is an int and that doesn't make any sense. What do you believe sumall should be?

like image 65
Free Monica Cellio Avatar answered Sep 22 '22 17:09

Free Monica Cellio


If you want to sum the digit of a number, one way to do it is using sum() + a generator expression:

sum(int(i) for i in str(155)) 

I modified a little your code using sum(), maybe you want to take a look at it:

birthday = raw_input("When is your birthday(mm/dd/yyyy)? ") summ = sum(int(i) for i in birthday[0:2]) sumd = sum(int(i) for i in birthday[3:5]) sumy = sum(int(i) for i in birthday[6:10]) sumall = summ + sumd + sumy print "The sum of your numbers is", sumall sumln = sum(int(c) for c in str(sumall))) print "Your lucky number is", sumln 
like image 22
Rik Poggi Avatar answered Sep 20 '22 17:09

Rik Poggi