Str to int


#1

hi the code:
courses = ["banane", "orange", "pomme"]

stock = { "banane": 6,
"pomme": 0,
"orange": 32,
"poire": 15
}

prix = { "banane": 4,
"pomme": 2,
"orange": 1.5,
"poire": 3
}

Ecrivez votre code ci-dessous :

def calculer_facture(course):
k = 0
for i in course:
print stock[i]
if int(stock[i]) == 0 or int(course[i]) > int(stock[i]):
k = k + int(prix[i]) * int(course[i])
stock[i] = 0
else:
k = k + int(prix[i]) * int(course[i])
stock[i] -= 1 * int(course[i])
return k

and the error:Oups, merci de réessayer. Appelant calculer_facture avec une liste contenant 1 pomme, 1 poire and 1 banane causé l'erreur suivante: list indices must be integers, not str


#2

Hi. Sorry, I don't speak French, so I am replying in English. The error is because you're using a string as an index, but an index must be an integer. Consider these lines:

Since course is a list, course[i] picks out the course list item at index i. But since you're in a for loop where i is the first item in the list, the value of i is a string. On the first time through the loop, i is "banane". And so you're saying, "find me the value of the list item in the course list at index position "banane"." But index positions are integers, not strings, so you receive an error message.