简体   繁体   中英

Why does increasing a variable by a list element give me an IndexError?

I am new to Python. I am trying to make a slot machine game and I keep getting this error:

totalScore += scores[score]
IndexError: list index out of range

Here is the code:

for dollars in range(money):
if money < 5:
    print("You don't have enough money to play anymore!")
    break
score = pyslot()
scores.append(score)
money -= 5

totalScore = 0
winnings = 0

for score in scores:
    totalScore += scores[score]
    if scores[score] < 20:
        winnings -= 5
    elif scores[score] < 50:
        winnings += 5
    elif scores[score] >= 50:
        winnings += 10

I'm not sure why Python is giving me this error. I don't know much about it but I thought that the "for score in scores" would keep this from happening.

for score in scores loops over the elements in scores . If scores is a list containing [50, 100, 200] you will get 50 in score in the first iteration; scores[50] is clearly out of bounds, and hence you get an IndexError .

If you actually want to loop over the positions in the array, try

for idx in range(len(scores)):
    totalScore += scores[idx]

but this is unnecessarily complex and slow here.

(There are situations where it makes a difference to your algorithm where in the sequence you are in each iteration. For example, if you wanted to compare the current scores[idx] to the adjacent scores in the list, that's somewhat hard to do if you loop directly over the items, but easy with scores[idx-1] and scores[idx+1] - obviously, you have to take care to avoid an IndexError at the first and last elements, but let's skip that complication here.)

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