You need to enable JavaScript to run this app. 为什么while循环没有遍历完整unconfirmed_users列表直到其为空?
优惠活动
大模型
产品
解决方案
定价
更多

为什么while循环没有遍历完整unconfirmed_users列表直到其为空?

故障原因

  • 问题出在代码缩进错误,Python依靠缩进来区分代码块归属:你的while循环下只有current_users = unconfirmed_users.pop()这一行属于循环体内的逻辑,后续的验证打印、将用户加入已确认列表的代码都放在了循环体外。
  • 实际执行流程是:while循环会持续弹出unconfirmed_users的末尾元素,直到列表为空才会退出循环,整个循环过程中不会执行打印、添加到已确认列表的操作,只有最后一次弹出的用户会被处理,所以看起来循环没有遍历所有元素、也没有正常执行完整操作。

修复方案

调整缩进,把打印和添加用户的逻辑放到while循环的缩进块内即可,修复后代码如下:

unconfirmed_users = ['mikey', 'ethan', 'bob']
confirmed_users = []

while unconfirmed_users:
    current_users = unconfirmed_users.pop()
    # 以下两行调整缩进,归入while循环的代码块
    print('Verifying user: ' + current_users.title())
    confirmed_users.append(current_users)

print('\nThe following users have been verified: ')
for users in confirmed_users:
    print(users.title())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 05:36:03