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

Python代码报错‘continue/break不在循环中’及‘Unreachable’原因排查

质数检查Python代码问题排查及修复

问题现象

运行质数检查代码时,控制台提示continue and break not in the loop,同时出现“Unreachable”代码提示,程序无法正常执行。期望输入25时,能显示其为合数,并询问是否继续测试。

错误原因分析

  1. while else块误用:代码末尾的else块属于while True循环,但while True是无限循环,仅能通过break退出,因此该else块永远不会执行,属于不可达代码。且块内的continue语句不在循环上下文内,直接触发语法错误。
  2. 合数分支错误退出循环:检测到合数时执行break,直接跳出while循环,跳过了询问是否继续的逻辑,不符合需求。
  3. 无输入异常处理:输入非整数时,int(integer)会抛出ValueError,程序直接崩溃,无法进入错误提示流程。
  4. 细节问题:
    • 质数检查的range(2, number-1)范围可优化,当前写法虽不影响结果,但效率较低;
    • 输出文本中divisible to是语法错误,应为divisible by。

修复后的代码

print("Prime Number Checker")

while True:
    # 输入处理,捕获非整数异常
    integer = input("\nEnter an integer to test: ")
    try:
        number = int(integer)
    except ValueError:
        print("Invalid integer value! Try again")
        continue
    
    is_prime = True
    divisor = None
    # 优化质数检查范围,仅需验证到平方根
    for i in range(2, int(number**0.5) + 1):
        if number % i == 0:
            is_prime = False
            divisor = i
            break
    # 处理小于2的特殊数值
    if number <= 1:
        print(f"{number} is not a prime or composite number")
    elif is_prime:
        print(f"{number} is a prime number")
    else:
        print(f"{number} is a composite number because it is divisible by {divisor}")
    
    # 询问是否继续测试
    option = input("Do you want to test another integer (y/n): ")
    if option.lower() == "n":
        break

print("Bye!")

验证结果

输入25时,输出与期望一致:

Enter an integer to test: 25
25 is a composite number because it is divisible by 5
Do you want to test another integer (y/n): y

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:00:16