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

Python质数求和程序无法保存历史结果的问题求助

问题修复方案

你的代码核心问题是列表初始化的位置错误:prime_result = []被写在了while True循环内部,每次循环都会重新创建一个空列表,之前添加的结果自然会被清空,无法实现累积存储。

修正后的代码

def PrimeNumber():
    prime_result = []  # 把列表初始化移到循环外,只创建一次
    while True:
        num1 = int(input("Give me the first number: "))
        num2 = int(input("Give me the second number: "))
        result = num1 + num2

        is_prime = True
        if result <= 1:
            is_prime = False
        else:
            # 优化质数判断:只需检查到平方根,减少不必要的计算
            for i in range(2, int(result**0.5) + 1):
                if result % i == 0:
                    is_prime = False
                    break
        
        if is_prime:
            print("The result of the sum is a prime!")
            prime_result.append(result)
        else:
            print("The result of the sum is not a prime!")
        
        # 每次操作后打印当前累积的质数结果
        print(f"Current prime sum results: {prime_result}")

PrimeNumber()

关键改动说明

  1. 调整列表初始化位置:将prime_result = []移到while True循环之前,确保整个函数执行期间只有一个列表实例,所有符合条件的结果都会追加到同一个列表中。
  2. 重构质数判断逻辑:用is_prime变量统一标记结果是否为质数,让代码结构更清晰,避免重复的打印逻辑。
  3. 优化质数判断效率:循环范围改为range(2, int(result**0.5) + 1),因为一个数若有因数,必然有一个不大于其平方根的因数,这样能减少循环次数,提升运行效率。
  4. 统一打印列表时机:每次输入处理完成后都打印当前的质数列表,不管是否新增了元素,方便随时查看累积结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 09:07:05