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

Python条件循环向列表加元素求和出现无限循环的解决方法

问题根因

代码进入无限循环的核心问题是while循环的判断变量没有在循环内更新:

  • 你在循环启动前第一次计算computer_score = sum(computer),此时空列表求和结果为0
  • 进入循环后,你仅执行了往列表加元素的操作,始终没有重新计算computer_score的最新值,判断条件里的computer_score永远是初始值0,永远满足<17的循环触发条件,因此程序会无限运行。
    另外你定义的another_card_computer函数中,for i in range(1)是完全多余的逻辑,这个循环固定只执行1次,没有存在必要。
修正后可运行代码
import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
computer = []

def another_card_computer():
    computer.append(random.choice(cards))

computer_score = sum(computer)
while computer_score < 17:
    another_card_computer()
    # 每次抽牌后重新计算最新分数,更新循环判断变量
    computer_score = sum(computer)

print(computer_score)
改动说明
  • 将分数计算逻辑computer_score = sum(computer)移入while循环内部,每次抽完新牌就同步更新当前总分,保证循环判断条件能拿到最新的分数值,在分数达到17及以上时正常退出循环
  • 删除抽牌函数中无意义的单层for循环,简化冗余逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 08:57:21