I’m trying to assign a new value to a key in a dictionary. But getting “ValueError: invalid literal for int() with base 10:”
Here is what I do.
balance = {'beer':5, 'toast':2}
item = input("what did you eat?: ")
price = input("how much?: ")
if item not in balance:
balance[item] = int(price)
else:
balance[item] = balance[item] + int(price)
I’m puzzled, since I can do balance[‘beer’] = 5 in python shell, what am I missing?
Read the error message again:
This means, that you are passing an invalid argument to function
int(), i.e. a string that does not represent a valid decimal number.Check what
pricename holds. As it’s taken from the user, your program must be prepared to handle a situation when it’s garbage. I usually make a function to handle the boilerplate:You can also add some escape condition if it makes sense in your program.