Python ValueError:以10为基数的int()的文本无效如何修复错误
我试图做一个随机的数学问题测验,但我不明白为什么我总是出错:Python ValueError:以10为基数的int()的文本无效如何修复错误,python,string,random,int,literals,Python,String,Random,Int,Literals,我试图做一个随机的数学问题测验,但我不明白为什么我总是出错: 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)
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)
回溯(最近一次呼叫最后一次):
文件“N:/Computer science/A453/Test.py”,第12行,在
打印(num1+int(ops)+num2)
ValueError:以10为底的int()的文本无效:'-'
>>> ================================
尝试强制num1和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: '-'
>>> ================================
为什么要尝试将随机选择从
'+'
、'-'
和'*'
转换为整数?你到底指望会发生什么?!像“+”
这样的字符串怎么可能被转换成整数呢?@JoachimPileborg只有在2.x中,在3.x中,你需要例如列表(op)
而不是操作键()
,因为你不能为dict键
对象编制索引。@jornsharpe我能做些什么来解决这个问题,因为我完全困惑了,你想做什么?是否要调用使用例如“+”
(即操作符.添加
)键控的函数?非常感谢,这是我唯一没有尝试的事情,非常感谢:)
print (str(num1) + ops + str(num2))