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