【问题标题】:calculate the content of a variable计算变量的内容
【发布时间】:2021-03-29 21:35:03
【问题描述】:
我在学习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
string
loops
variables
calculation
【解决方案1】:
你不需要循环:
a = input()
operator = a.split()[0]
number1 = a.split()[1]
number2 = a.split()[2]
equation = (number1 + ' ' + operator + ' ' + number2)
print(equation)
【解决方案2】:
您不需要循环来获取整个句子。只需输入即可,因为 split() 用于按给定参数拆分字符串。只需使用 a = input()。
【解决方案3】:
x = '+ 9 16'
operator, number1, number2 = x.split()
result = eval(number1 + ' ' + operator + ' ' + number2) #ugly
print(result)
你可以试试
print(eval(equation)) #ugly
【解决方案4】:
表达式是一个前缀表达式,其中运算符是第一个,后面是操作数。 + 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
为了评估更复杂的前缀表达式,我们通常使用 stack。要了解有关评估复杂前缀表达式的更多信息,请参阅 this。