简体   繁体   中英

Why am i getting index of the range error?

def oburparaust(liste, money):
moneycontrol = 0.0
coin=0
control = 0
while True:
    if liste[control] > money:
        control+=1
    else:
        moneycontrol+=liste[control]
        coin+=1
        if moneycontrol==money:
            break
        elif moneycontrol > money:
            moneycontrol-=liste[control]
            coin-=1
            print(moneycontrol)
            if control>len(liste)-1:
                print(moneycontrol)
                control=len(liste)-1
            else:
                control+=1
    #print(coin)
oburparaust([1.0, 0.50, 0.25, 0.10, 0.05, 0.01], 5.38)

I want to calculate how much coin was used for the money of 5.38. but i get index of the range error i couldn't find why where am i going over the list?

Error;

Traceback (most recent call last):
     File "xxxx", line 26, in 
     oburparaust([1.0, 0.50, 0.25, 0.10, 0.05, 0.01], 5.38)
     File "xxxx", line 6, in oburparaust
     if liste[kontrol] > a:
     IndexError: list index out of range
     moneycontrol:  1.0    Coin:  1
     moneycontrol:  2.0    Coin:  2
     moneycontrol:  3.0    Coin:  3
     moneycontrol:  4.0    Coin:  4
     moneycontrol:  5.0    Coin:  5
     moneycontrol:  5.0    Coin:  5
     moneycontrol:  5.0    Coin:  5
     moneycontrol:  5.25    Coin:  6
     moneycontrol:  5.25    Coin:  6
     moneycontrol:  5.35    Coin:  7
     moneycontrol:  5.35    Coin:  7
     moneycontrol:  5.35    Coin:  7
     moneycontrol:  5.359999999999999    Coin:  8
     moneycontrol:  5.369999999999999    Coin:  9
     moneycontrol:  5.379999999999999    Coin:  10
     moneycontrol:  5.379999999999999    Coin:  10

You have list "liste" with 6 items, what means that your index starts with 0 and ends with 5, in the point when your variable control will have value 6, index will be out of the range. you will need to control that variable "control" if it is less than length of your list "liste". Something like:

def oburparaust(liste, money):
    moneycontrol = 0.0
    coin=0
    control = 0
    while control < len(liste):
           . . . 

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