长话短说,我正在为随机总和制作代码,并且已经开始使用运算符导入以使其更容易和更有效。但是,在打印结果时:
from operator import add, sub, mul
ops = (add, sub, mul)
op = random.choice(ops)
print("What is",ranNum1,op,ranNum2,"?")
我明白了:
什么是9<内置功能子> 3?
我试图删除结果中的字母,但它是一个tupple,而不是一个字符串,所以这是不可能的。有什么建议吗?
答案 0 :(得分:2)
您可以使用__name__
获取名称,但这不是符号运算符:
>>> print("What is", ranNum1, op.__name__, ranNum2, "?")
What is 6 add 9 ?
>>> print("Answer:", op(ranNum1, ranNum2))
Answer: 15
添加字典允许您打印符号运算符,因此将ops
替换为字典:
>>> ops = {add: '+', mul: '*', sub: '-'}
>>> op = random.choice(list(ops))
>>> print("What is", ranNum1, ops[op], ranNum2, "?")
What is 6 + 9 ?
答案 1 :(得分:-1)
from operator import add, sub, mul
import random
ranNum1 = random.randint(0, 100)
ranNum2 = random.randint(0, 100)
ops = {'+': add, '-': sub, '*': mul}
op = random.choice(list(ops.keys()))
while True:
user_input = int(input('What is {0} {1} {2}?'.format(ranNum1, op, ranNum2)))
if user_input == ops.get(op)(ranNum1, ranNum2):
break
print('Incorrent!')
print('Correct!')