【问题标题】:ValueError: invalid literal for int() with base 10 How to fix errorValueError:int() 的无效文字,基数为 10 如何修复错误
【发布时间】:2015-02-10 12:07:52
【问题描述】:
import random
import operator


op = {"+":operator.add,
      "-":operator.sub,
      "*":operator.mul}
num1 = random.randint(0,10)
num2 = random.randint(0,10)
ops = random.choice(list(op.keys()))
print (num1 + int(ops) + num2)

我正在尝试进行随机数学问题测验,但我无法弄清楚为什么我不断收到错误:

Traceback (most recent call last):
  File "N:/Computer science/A453/Test.py", line 12, in <module>
    print (num1 + int(ops) + num2)
ValueError: invalid literal for int() with base 10: '-'
>>> ================================ 

【问题讨论】:

  • 您为什么要将随机选择从'+''-''*' 转换为整数?你到底期望会发生什么?!
  • 怎么会有一个像 e.g. 这样的字符串? "+" 曾经被转换为整数吗?
  • @JoachimPileborg 仅在 2.x 中,在 3.x 中您需要例如list(op) 而不是 op.keys(),因为您无法索引 dict_keys 对象。
  • @jonrsharpe 那么我该怎么做才能解决这个问题,因为我完全感到困惑
  • 你想完成什么?你想调用例如键控的函数吗? "+"(即operator.add)?

标签: python string random int literals


【解决方案1】:

尝试在 num1 和 num2 上强制使用字符串。由于您使用 + 进行操作,因此您应该使用字符串进行操作。

print (str(num1) + ops + str(num2))

【讨论】:

  • 非常感谢,这是我唯一没有尝试过的,非常感谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 2016-11-14
  • 2021-08-06
  • 2018-09-05
  • 2021-12-18
  • 1970-01-01
相关资源
最近更新 更多