gpt4 book ai didi

python - 如何使用算术符号而不是内置函数

转载 作者:行者123 更新时间:2023-11-28 17:37:16 25 4
gpt4 key购买 nike

我正在用 Python 进行数学测验,并使用了 3 个运算符:加法、减法和乘法。我想使用算术运算符,但我发现这很困难,因为如果我只是打印它,python 只是将它读取为一个符号。我使用以下代码:

import random
import operator
opslist = [ # This is the bit that I want to change, i also want
operator.add, # the operators all on one line
operator.sub,
operator.mul
]

num1 = random.randint(1,10) # These are two random numbers for my quiz
num2 = random.randint(1,10)
ops = random.choice(opslist) #Random operator for my quiz

total = (ops(num1,num2)) # Answer for my quiz

print (num1,ops,num2) # Random question for my quiz

这是输出:

6 <built-in function add> 5

1.) 如何使输出为“6+5”

2.) 另外,我如何让数字只进行小的计算,从而得到肯定的答案,这样问题就永远不会是像“5-8”这样的问题了

最佳答案

我也会在您的代码中使用字典。这就是我所做的。

import random
import operator

opslist= {
operator.add: "+", # the operators all on one line
operator.sub: "-",
operator.mul: "x"
}

num1 = random.randint(1,10) # These are two random numbers for my quiz
num2 = random.randint(1,10)
ops = random.choice(list(opslist.keys())) #Random operator from opslist keys

total = (ops(num1,num2)) # Answer for my quiz

print(num1,opslist[ops],num2)

打印问题时,程序会为运算符(operator)打印出符号。为确保您不会得到负数,请在总计下添加:

while total < 0:
num1 = random.randint(1,10)
num2 = random.randint(1,10)
ops = random.choice(opslist)

total = (ops(num1,num2))

关于python - 如何使用算术符号而不是内置函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29177501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com