Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ValueError:以10为基数的int()的文本无效如何修复错误_Python_String_Random_Int_Literals - Fatal编程技术网

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))