评估数学表达式(Python)

2024-06-02 09:09:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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?我需要代码来处理所有操作。在


Tags: or用户inputifspacefindintprint
1条回答
网友
1楼 · 发布于 2024-06-02 09:09:28

我会建议你这样做,我认为你 解析输入表达式中的值可能过于复杂。在

您只需对输入字符串调用.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))

相关问题 更多 >