如何在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
elifwithout an initialifstatement—Python needs a startingifto evaluate conditions properly. - Operators like
+need to be wrapped in quotes (e.g.,"+") since you're comparing against a string input fromraw_input(). - You're missing colons (
:) at the end of eachif/elifline, which is required for Python's block structure.
- You're using
修正后的完整代码
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 withint()if you only need whole numbers). Thetry/exceptblock catches cases where the user enters non-numeric text. - Proper conditionals: We start with an
ifstatement, follow up withelifs, and end with anelseto 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
相关产品推荐
相关产品推荐

