TypeError: 'int' object is not subscriptable

前端 未结 6 564
一生所求
一生所求 2020-12-13 09:08

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, i         


        
相关标签:
6条回答
  • 2020-12-13 09:25

    Just to be clear, all the answers so far are correct, but the reasoning behind them is not explained very well.

    The sumall variable is not yet a string. Parentheticals will not convert to a string (e.g. summ = (int(birthday[0])+int(birthday[1])) still returns an integer. It looks like you most likely intended to type str((int(sumall[0])+int(sumall[1]))), but forgot to. The reason the str() function fixes everything is because it converts anything in it compatible to a string.

    0 讨论(0)
  • 2020-12-13 09:30

    You can't do something like that: (int(sumall[0])+int(sumall[1]))

    That's because sumall is an int and not a list or dict.

    So, summ + sumd will be you're lucky number

    0 讨论(0)
  • 2020-12-13 09:32
    sumall = summ + sumd + sumy
    

    Your sumall is an integer. If you want the individual characters from it, convert it to a string first.

    0 讨论(0)
  • 2020-12-13 09:40

    Try this instead:

    sumall = summ + sumd + sumy
    print "The sum of your numbers is", sumall
    sumall = str(sumall) # add this line
    sumln = (int(sumall[0])+int(sumall[1]))
    print "Your lucky number is", sumln
    

    sumall is a number, and you can't access its digits using the subscript notation (sumall[0], sumall[1]). For that to work, you'll need to transform it back to a string.

    0 讨论(0)
  • 2020-12-13 09:43

    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?

    0 讨论(0)
  • 2020-12-13 09:44

    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
    
    0 讨论(0)
提交回复
热议问题