You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python四则运算代码以支持多操作符复杂表达式?

How to Support Full Arithmetic Expressions in Your Python Code

Hey there! The problem with your current code is that it only looks for one operator at a time and splits the equation once—so it can't handle multiple operations, nor does it respect the order of operations (you know, multiplication/division before addition/subtraction). Let's go over two solid ways to fix this.

Quick Fix: Use eval() (but be cautious)

The simplest way to handle any valid arithmetic expression is to use Python's built-in eval() function, which parses and evaluates string expressions directly. Here's how you can rewrite your code:

try:
    equation = input('Enter an equation: ')
    result = eval(equation)
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Error! You can't divide by zero.")
except SyntaxError:
    print("Error! Please enter a valid arithmetic expression using +, -, *, /.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Important Note:

eval() is powerful, but never use it with untrusted input (like user input from a website or unknown source). It will execute any Python code passed to it, which is a huge security risk. This is great for personal use or trusted environments, but not for production systems.

More Robust Solution: Implement Expression Parsing (For Learning & Safety)

If you want to avoid eval() and understand how arithmetic expressions are evaluated, you can implement a parser that respects operator precedence. Here's a basic version that handles +, -, *, / with proper order of operations:

def evaluate_expression(equation):
    # Split the equation into numbers and operators (tokenization)
    tokens = []
    current_num = ""
    for char in equation:
        if char in "+-*/":
            if current_num:
                tokens.append(float(current_num))
                current_num = ""
            tokens.append(char)
        elif char.isdigit() or char == ".":
            current_num += char
        elif char.isspace():
            continue  # Ignore spaces in input
        else:
            raise ValueError("Invalid character in expression")
    if current_num:
        tokens.append(float(current_num))
    
    # First handle multiplication and division (higher precedence)
    i = 1
    while i < len(tokens):
        if tokens[i] in "*/":
            num1 = tokens[i-1]
            op = tokens[i]
            num2 = tokens[i+1]
            if op == "*":
                res = num1 * num2
            else:
                if num2 == 0:
                    raise ZeroDivisionError("Division by zero")
                res = num1 / num2
            # Replace the operation with its result
            tokens = tokens[:i-1] + [res] + tokens[i+2:]
        else:
            i += 1
    
    # Now handle addition and subtraction (lower precedence)
    result = tokens[0]
    i = 1
    while i < len(tokens):
        op = tokens[i]
        num = tokens[i+1]
        if op == "+":
            result += num
        else:
            result -= num
        i += 2
    
    return result

try:
    equation = input('Enter an equation: ')
    result = evaluate_expression(equation)
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Error! You can't divide by zero.")
except ValueError as e:
    print(f"Error: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

How This Works:

  1. Tokenization: We first split the input string into numbers (as floats) and operators, ignoring any spaces.
  2. Process High-Precedence Operations: We iterate through the tokens and compute all * and / operations first. We replace each operation with its result, shrinking the token list as we go.
  3. Process Low-Precedence Operations: Once all multiplication/division is done, we compute the remaining + and - operations left to right.

This approach is safer than eval() because it only handles the specific arithmetic operations you allow, and you have full control over the evaluation process.

Final Thoughts

  • Use eval() for quick, personal scripts where you trust the input completely.
  • Use the custom parser if you need to restrict input types, learn how expression evaluation works under the hood, or build something for a production environment.

内容的提问来源于stack exchange,提问作者Noob Saibot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:01:43