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

Python计算器程序出现Code is unreachable问题,寻求解决方法

问题解决:代码不可达与函数调用错误

核心问题1:代码不可达(Code is unreachable)

你的Add()函数定义放在了while True无限循环之后——Python解释器按从上到下的顺序执行代码,一旦进入这个无限循环,后面的函数定义永远不会被执行到,所以IDE会提示“代码不可达”,实际运行时调用Add()还会直接报NameError,因为函数还没被定义。

修复方式:把Add()函数的定义移到while循环之前,确保调用函数时它已经存在。

核心问题2:数字与字符串拼接错误

Add()里的print(answer + "is your answer.")会触发TypeError,因为answer是浮点数,不能直接和字符串相加。你可以用f-string格式化输出,或者把数字转成字符串再拼接。

额外优化建议

  • 避免全局变量:把num_1和num_2作为参数传给Add(),比依赖全局变量更清晰,也避免意外的变量污染。
  • 合并条件判断:把多个独立的if改成if-elif-else,减少不必要的判断分支。
  • 清理无用代码:import math、i=101、j=102这些没用到的代码可以先删掉,让代码更整洁。
  • 处理除数为0的情况:除法分支里加个判断,避免运行时崩溃。

修复后的完整代码

num_1 = 0
num_2 = 0
operator = 'x'

def Add(a, b):
    answer = a + b
    print(f"{answer} is your answer.")

while True:
    begin = input("Welcome to calculator. Type start to begin, and q to quit ")
    if begin == 'start':
        num_1 = float(input("Enter the first number: "))
        num_2 = float(input("Enter the second number: "))
        operator = input("Enter the function ('*' for multiplication,\n '/' for division,\n '+' for addition,\n '-' for subtraction. (Case Sensitive))")
        if operator == "*":
            print(f"{num_1 * num_2} is your answer.")
        elif operator == "/":
            if num_2 == 0:
                print("Error: Cannot divide by zero.")
            else:
                print(f"{num_1 / num_2} is your answer.")
        elif operator == "+":
            Add(num_1, num_2)
        elif operator == "-":
            print(f"{num_1 - num_2} is your answer.")
        else:
            print("Invalid operator, please enter one of *, /, +, -")
    elif begin == 'q':
        print("quitting program...")
        break  # 用break退出循环比exit()更规范
    else:
        print("You must type 'start', or 'q'(Case sensitive)")

修复细节说明

  1. 函数定义前置,解决了代码不可达和未定义的问题。
  2. 给Add()添加参数,替代全局变量,代码逻辑更清晰。
  3. 使用f-string格式化输出,解决了类型拼接错误。
  4. 改用elif优化条件判断,减少无效检查。
  5. 增加除数为0的错误处理,提升程序健壮性。
  6. 用break替代exit()退出循环,符合Python的代码习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:27:01