使用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
问题分析
- 判断条件错误:你想跳过状态为"off"的用户,但代码里写的是
status_lst[i] == "cat",完全不匹配状态列表里的值,等于没过滤任何用户。 - 死循环陷阱:当
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
相关产品推荐
相关产品推荐

