Python 计算变量的内容

Python 计算变量的内容,python,string,loops,variables,calculation,Python,String,Loops,Variables,Calculation,我正在学习python,我遇到了一个问题 for i in input: operator = i.split()[0] number1 = i.split()[1] number2 = i.split()[2] equation = (number1 + ' ' + operator + ' ' + number2) 此代码用于计算随机生成的输入,例如: +9 16 这个要我打印9+16的结果 所以我编写了代码,将输入转换成一个方程,但我不知道如何告诉代码来

我正在学习python,我遇到了一个问题

for i in input:
    operator = i.split()[0]
    number1 = i.split()[1]
    number2 = i.split()[2]
    equation = (number1 + ' ' +  operator + ' ' + number2)
此代码用于计算随机生成的输入,例如:

+9 16
这个要我打印9+16的结果

所以我编写了代码,将输入转换成一个方程,但我不知道如何告诉代码来计算它

有人能帮我吗?

您不需要循环:

a = input()
operator = a.split()[0]
number1 = a.split()[1]
number2 = a.split()[2]
equation = (number1 + ' ' +  operator + ' ' + number2)
print(equation)

你不需要一个循环就能得到整个句子。由于split()用于按给定参数拆分字符串,因此只需输入即可。只需使用a=input()

在你的情况下,你可以试试

print(eval(equation)) #ugly

表达式是一个前缀表达式,其中运算符是第一个,后跟操作数
+9 16
是一个简单的表达式,因为这里只有一个运算符,即
+
和两个操作数
9
16

def evaluate(num1, num2, operator):
    # returns the result after evaluating the expression
    if operator == '+': 
        return(num1 + num2) 

    elif operator == '-': 
        return(num1 - num2) 

    elif operator == '*': 
        return(num1 * num2) 

    elif operator == '/': 
        return(num1 / num2)


a = str(input())
# a = "+ 9 16"

temp = None
operator = ""

for i in a.split():
    # a.split() is a list
    if i.isdigit():
        # isdigit() returns true if i is a number
        if not temp:
            # this is our first operand
            temp = int(i) 
        else:
            # this is our second operand
            print(evaluate(temp, int(i), operator))
    else:
        # this is our operator
        operator = i
为了计算更复杂的前缀表达式,我们通常使用堆栈。要了解有关计算复杂前缀表达式的详细信息,请参阅

def evaluate(num1, num2, operator):
    # returns the result after evaluating the expression
    if operator == '+': 
        return(num1 + num2) 

    elif operator == '-': 
        return(num1 - num2) 

    elif operator == '*': 
        return(num1 * num2) 

    elif operator == '/': 
        return(num1 / num2)


a = str(input())
# a = "+ 9 16"

temp = None
operator = ""

for i in a.split():
    # a.split() is a list
    if i.isdigit():
        # isdigit() returns true if i is a number
        if not temp:
            # this is our first operand
            temp = int(i) 
        else:
            # this is our second operand
            print(evaluate(temp, int(i), operator))
    else:
        # this is our operator
        operator = i