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`
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.
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.
The objects that contain other objects or data types, like strings, lists, tuples, and dictionaries, are 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.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With