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

如何在Python中根据运算符处理变量?简易计算器开发求助

解决你的简易计算器问题

Hey SanguineL, let's work through your calculator issues one by one—you're almost there! 🛠️

核心问题分析

Your code has a few small but critical issues that are stopping it from working:

  • Input type mismatch: raw_input() returns strings, not numbers. You can't do math operations like + or - on strings directly (they'll just concatenate instead of adding).
  • Syntax errors:
    • You're using elif without an initial if statement—Python needs a starting if to evaluate conditions properly.
    • Operators like + need to be wrapped in quotes (e.g., "+") since you're comparing against a string input from raw_input().
    • You're missing colons (:) at the end of each if/elif line, which is required for Python's block structure.

修正后的完整代码

Here's a fixed version that handles input conversion, proper conditionals, and basic error handling:

# Get inputs and convert to floats (supports decimals!)
try:
    number1 = float(raw_input("What is the first number? "))
    operator = raw_input("What is the operator? (+, -, *, /) ").strip()
    number2 = float(raw_input("What is the second number? "))
except ValueError:
    print("Oops! Please enter valid numbers.")
    exit()

# Calculate based on operator
if operator == "+":
    answer = number1 + number2
elif operator == "-":
    answer = number1 - number2
elif operator == "*":
    answer = number1 * number2
elif operator == "/":
    if number2 == 0:
        print("Error: Can't divide by zero!")
        exit()
    answer = number1 / number2
else:
    print(f"Unknown operator: {operator}. Please use +, -, *, or /")
    exit()

# Output the result
print(f"{number1} {operator} {number2} = {answer}")

关键改进点

  • Input conversion: We use float() to turn string inputs into numbers (swap with int() if you only need whole numbers). The try/except block catches cases where the user enters non-numeric text.
  • Proper conditionals: We start with an if statement, follow up with elifs, and end with an else to handle invalid operators gracefully.
  • Error handling: Added checks for division by zero and invalid inputs, so the program doesn't crash unexpectedly.
  • Clean formatting: Added .strip() to the operator input to ignore accidental spaces, and used f-strings for clear, readable output.

测试示例

If you run this code and enter:

What is the first number? 10
What is the operator? (+, -, *, /) *
What is the second number? 5

You'll get:

10.0 * 5.0 = 50.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:26:48