python - 将用户输入运算符分配给变量

标签 python python-3.x

我正在尝试设置一种情况,在这种情况下,用户输入一个数字和一个运算符,输出是 1 到 10 列表中的(用户编号)(用户运算符)。

这很难解释,但这是代码:

num = int(input("Enter a number greater than 1: "))

oper = input("Choose a math operation (+, -, *): ")
for i in range(1, 11):
    print(num)

然后我迷路了。我想得到看起来像的东西

num   oper   1   =   (whatever num and the operator and 1 equal)
num   oper   2   =   (whatever num and the operator and 2 equal)

等等。

所以我的问题是:如何将用户输入的运算符分配给变量?

最佳答案

另一种可能性是使用 operator模块来设置运算符函数的字典,如下所示:

import operator

operator_dict = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
}
num = int(input("Enter a number greater than 1: "))

oper = input("Choose a math operation (+, -, *): ")
for i in range(1, 11):
    print(operator_dict[oper](float(num), i))

示例 session :

Enter a number greater than 1: 3
Choose a math operation (+, -, *): *
3.0
6.0
9.0
12.0
15.0
18.0
21.0
24.0
27.0
30.0

关于python - 将用户输入运算符分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35006303/

相关文章:

python-3.x - 使用 imageio.ffmpeg.download() 时出现弃用错误

python - Keras model.fit() 发出 TypeError : 'NoneType' object is not callable

python - 使用 pexpect 跳过子进程的 stdin 和 stderr

python - 如何优化Python pandas中的数据透视表代码

用于查找未转义字符的 Python 正则表达式

python - 如何迭代一个既可以是整数又可以是数组的变量?

python - 当以 f(x)(y) 格式调用 Python 函数时,这意味着什么?

python - 在单元测试中使用模拟来修补 sleep

Python:在无限循环函数中只运行一次代码段..?

python - OpenCv错误无法通过视频捕获打开相机