-1

我正在尝试为字典中的键分配一个新值。但是得到“ValueError:int()的无效文字,以10为基数:”这就是我所做的。

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)

我很困惑,因为我可以在 python shell 中做 balance['beer'] = 5,我错过了什么?

4

2 回答 2

2

什么是价值price

它可能是一个字符串?

具有无法转换为的值int将导致此

>>> test = 'test'
>>> int(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'test'

还请确保发布您的完整回溯,因为 python 在您的问题中提供给您,而不仅仅是错误字符串

这是了解数据验证的好机会,因为您可以看到您的程序需要一个整数。您可以自己处理这个问题,向用户显示您自己的消息,或者允许程序出错(假设您的程序的客户端会理解错误)

数据验证没有捷径

try:
  price = int(input("how much?: "))
catch ValueError:
  print('Please enter an integer')

或类似的东西

于 2012-12-09T22:32:36.797 回答
2

再次阅读错误信息:

ValueError: invalid literal for int() with base 10

这意味着,您向 function 传递了一个无效参数int(),即一个不代表有效十进制数的字符串。

检查什么price名称。由于它是从用户那里获取的,因此您的程序必须准备好处理垃圾的情况。我通常会创建一个函数来处理样板:

def input_int(prompt):
    while True:
        data = input(prompt)
        try:
            return int(data)
        except ValueError:
            print("That's not a valid number. Try again.")

如果在您的程序中有意义,您还可以添加一些转义条件。

于 2012-12-09T22:33:37.517 回答