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

求助: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 print statement, you used num1 and num2, but you defined your input variables as a and b. This will throw a NameError because those num1/num2 variables don't exist in your code.
  • Unhandled Division by Zero: If the user enters 0 as the second number and picks division, your program will crash with a ZeroDivisionError. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 22:22:27