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

时间:2016-01-26 02:51:59

标签: 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)

等等。

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

5 个答案:

答案 0 :(得分:3)

从你在这里说的话:

  

我正在尝试设置一个用户输入数字和的情况   操作员和输出是a上的(用户编号)(用户操作员)   列表1到10。

我想你想这样做:

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

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

答案 1 :(得分:3)

好像你想要这样的东西:

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

oper = raw_input("Choose a math operation (+, -, *): ")
for i in range(1, 11):
    if oper == '+':
        print(num, oper, i, '=', num + i)
    elif oper == '-':
        print(num, oper, i, '=', num - i)
    elif oper == '*':
        print(num, oper, i, '=', num * i)
    else:
        print('operator is not supported')

输出:

Enter a number greater than 1: 2
Choose a math operation (+, -, *): *
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

答案 2 :(得分:3)

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

答案 3 :(得分:1)

Eval can be used here:

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

oper = str(input("Choose a math operation (+, -, *, /, %, //): "))
if oper in ["+", "-", "*", "/", "%", "//"]:
    for i in range(1, 11):
        operation = num + oper + str(i) #Combine the string that is the operation
        print("{} {} {} = {}".format(num,oper,str(i),eval(operation)))
else: #if it is not in our approved items
    print("Operation not supported.")

答案 4 :(得分:1)

我认为最简单的方法是创建一个函数,它本身具有所有这些if / elif条件,因为python不会将字符串识别为运算符。

该功能可能看起来有点像:

def operation(number1, number2, operator):
    if operator == '+':
        return number1 + number2
    elif operator == '-':
        return number1 - number2

等等。然后你可以在for循环中调用这个函数,如下所示:

for n in range(10):
    otherNumber = n + 1
    print(yourNumber, otherNumber, operator)