【问题标题】:Evaluating a mathematical expression (python) [closed]评估数学表达式(python)[关闭]
【发布时间】:2016-11-07 06:00:53
【问题描述】:
print('Enter a mathematical expression: ')  
expression = input()  
space = expression.find(' ')  
oprand1 = expression[0 : space]  
oprand1 = int(oprand1)  
op = expression.find('+' or '*' or '-' or '/')  
oprand2 = expression[op + 1 : ]  
oprand2 = int(oprand2)  
if op == '+':  
 ans = int(oprand1) + int(oprand2)  
 print(ans)  

假设用户输入 2 + 3,每个字符之间有一个空格。我如何让它打印 2 + 3 = 5?我需要代码来处理所有操作。

【问题讨论】:

  • 你用的是哪个版本的python? stackoverflow.com/questions/1093322/…
  • Anaconda spyder
  • 可以打印import syssys.version的结果吗
  • 您没有正确使用find。提供的解决方案应该为您提供另一种方法。但是,如果您想尝试自己解决这个问题,请重新考虑您在 find 周围的工作。

标签: python string int find mathematical-expressions


【解决方案1】:

我会建议一些类似的东西,我认为你 从输入表达式中解析值可能过于复杂。

您可以简单地在输入字符串上调用 .split() 方法,默认情况下该方法 在空格 ' ' 上拆分,因此字符串 '1 + 5' 将返回 ['1', '+', '5']。 然后,您可以将这些值解压缩到您的三个变量中。

print('Enter a mathematical expression: ')  
expression = input()  
operand1, operator, operand2 = expression.split()
operand1 = int(operand1)
operand2 = int(operand2)  
if operator == '+':  
 ans = operand1 + operand2  
 print(ans)
elif operator == '-':
    ...
elif operator == '/':
    ...
elif operator == '*':
    ...
else:
    ...  # deal with invalid input

print("%s %s %s = %s" % (operand1, operator, operand2, ans))

【讨论】:

  • 你能解释一下这三个点是什么意思,“%s %s %s = %s”是什么意思吗?
  • 当然!我只是做了 ... 表示您可以像上一个一样填写这些部分。这不是实际的代码。
  • %s 是一个格式字符串,您可以提供值(在本例中为运算符和操作数以及答案)。每个 %s 对应于您在 % 之后传入的值。一开始我觉得他们很困惑。我认为有一个 string.format 方法实际上是更好的做法。所以你也可以阅读它
  • 在字符串格式方面,最后一行看起来像print("{} {} {} = {}".format(operand1, operator, operand2, ans))
猜你喜欢
  • 2011-06-30
  • 2010-12-05
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多