求助:Python用户输入双数算术运算程序报错排查及正确代码实现
Fixing Your Python Arithmetic Program Issues
Hey there! Let's break down what's going wrong with your code and get it working smoothly:
Identified Problems
- Mismatched Variable Names: In your final
printstatement, you usednum1andnum2, but you defined your input variables asaandb. This will throw aNameErrorbecause thosenum1/num2variables don't exist in your code. - Unhandled Division by Zero: If the user enters
0as the second number and picks division, your program will crash with aZeroDivisionError. We need to add a safety check for this scenario. - Accidental Whitespace in Input: If the user adds a space around the operator (like
+instead of+), your code will treat it as an invalid input. A quick cleanup of the input can fix this.
Corrected Code
# Get user inputs and convert to integers a = int(input("Enter First Number: ")) b = int(input("Enter Second Number: ")) print("Enter which operation would you like to perform?") # Strip extra whitespace to handle accidental spaces around the operator op = input("Enter any of these char for specific operation +,-,*,/: ").strip() result = 0 operation_valid = True if op == '+': result = a + b elif op == '-': result = a - b elif op == '*': result = a * b elif op == '/': # Prevent division by zero error if b == 0: print("Error: Cannot divide by zero!") operation_valid = False else: result = a / b else: print("Error: Invalid operation entered!") operation_valid = False # Only print the result if the operation was valid if operation_valid: print(a, op, b, ":", result)
Key Fixes & Improvements
- Fixed the variable name mismatch in the final print statement
- Added a check to avoid division by zero crashes
- Used
.strip()on the operator input to handle accidental spaces - Added a flag to ensure we only print results when the operation was successful
内容的提问来源于stack exchange,提问作者Abhinav PS
相关产品推荐
相关产品推荐

