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

使用while循环与continue语句筛选状态为on的用户信息异常排查

问题排查:while循环+continue打印指定状态用户信息

你想用while循环结合continue语句,只输出状态为"on"的用户账号密码,但代码运行后只输出了第一个用户的信息,和预期不符。

原代码

name_lst = ["koala", "cat", "fox", "hin"]
pw_lst = ["1111", "2222", "3333", "4444"]
status_lst = ["on", "off", "on", "off"]

i=0
while i < len(name_lst):
if status_lst[i] == "cat":
    continue
print("username: " + name_lst[i])
print("password: " + pw_lst[i])
i = i+1

问题分析

  1. 判断条件错误:你想跳过状态为"off"的用户,但代码里写的是status_lst[i] == "cat",完全不匹配状态列表里的值,等于没过滤任何用户。
  2. 死循环陷阱:当continue执行时,会直接跳过后续代码回到循环开头,但此时i没有递增,导致程序一直卡在i=1的位置循环,永远处理不了后面的用户。

修正后的代码

name_lst = ["koala", "cat", "fox", "hin"]
pw_lst = ["1111", "2222", "3333", "4444"]
status_lst = ["on", "off", "on", "off"]

i=0
while i < len(name_lst):
    if status_lst[i] == "off":
        i += 1  # 先递增索引,再跳过当前循环
        continue
    print("username: " + name_lst[i])
    print("password: " + pw_lst[i])
    i = i+1

运行结果

username: koala
password: 1111
username: fox
password: 3333

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:45:36