是 python 中归类为整数的数学运算符

is a mathematical operator classed as an interger in python

在python中是一个归类为整数的数学运算符。 例如,为什么这段代码不起作用

import random

score = 0
randomnumberforq = (random.randint(1,10))
randomoperator = (random.randint(0,2))
operator = ['*','+','-']
answer = (randomnumberforq ,operator[randomoperator], randomnumberforq)
useranswer = input(int(randomnumberforq)+int(operator[randomoperator])+      int(randomnumberforq))
if answer == useranswer:
print('correct')
else:
    print('wrong')

您尝试将字符串转换为整数,但它不是数字:

int(operator[randomoperator])

数组"operator"中的运算符是字符串,不代表数字,不能转换为整数值。另一方面,input() 函数需要字符串作为参数值。所以写:

... = input(str(numberValue) + operatorString + str(nubmerValue))

+ 运算符可用于连接字符串。但是Python要求两边的操作数都是字符串。这就是为什么我添加了 str() 函数以将数值转换为字符串的原因。

您不能只将一个运算符连接到几个数字并期望它被计算。您可以使用 eval 来评估最终字符串。

answer = eval(str(randomnumberforq)
              + operator[randomoperator] 
              + str(randomnumberforq))

完成您的尝试的更好方法是使用 operator 模块中的函数。通过将函数分配到列表中,您可以选择随机调用哪一个:

import random
from operator import mul, add, sub    

if __name__ == '__main__':
    score = 0
    randomnumberforq = random.randint(1,10)
    randomoperator = random.randint(0,2)
    operator = [[mul, ' * '],
                [add, ' + '], 
                [sub, ' - ']]
    answer = operator[randomoperator][0](randomnumberforq, randomnumberforq)
    useranswer = input(str(randomnumberforq) 
                       + operator[randomoperator][1] 
                       + str(randomnumberforq) + ' = ')
    if answer == useranswer:
        print('correct')
    else:
        print('wrong')

这取决于您要做什么。您没有向我们提供示例输入或输出、没有评论,也没有错误消息。

您似乎正在尝试编写一个简单的算术练习引擎。如果是这样,那么你的基本问题是你不了解编程中允许的操作。您不能只是将符号连续输入并期望计算机弄清楚它应该如何组合它们。您对 answer 和 useranswer 的分配语句在结构上有缺陷。第一个给你一个字符串列表;第二个死了,因为你试图将一个符号(比如 *)转换为一个整数。

对于更高级的用户,我会推荐"evaluate"操作。然而,对你来说... 当您选择随机运算符时,您需要检查您得到的是哪一个。写一个 3-branched "if" 来处理这三种可能性。这是第一个头部的样子:

if randomoperator == 0:
    operator = '*'
    answer = randomnumberforq * randomnumberforq
elif: ...

注意运算中的两个数是相同的。如果你想要不同的数字,你必须调用 randint 两次。

这会让您……在您感到舒服的编码水平上前进吗?