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

新手上路,请多包涵

我正在尝试设置一种情况,在这种情况下,用户输入一个数字和一个运算符,输出是 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)

等等。

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

原文由 chrono 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 235
1 个回答

另一种可能性是使用 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))

示例会话:

 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

原文由 JCVanHamme 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题