[英]python while loop with continue statement
我正在尝试使用“while loop”打印用户名和密码,并且只想打印“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
预期结果应该是:
username: koala
password: 1111
username: fox
password: 3333
但是,我只得到以下结果。
username: koala
password: 1111
缩进不好,它应该是status_lst[i] == "off"
而不是"cat"
并且你已经创建了一个无限循环,因为当你继续时你不增加这里是正确的代码:
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 = i+1
continue
print("username: " + name_lst[i])
print("password: " + pw_lst[i])
i = i+1
当你可以在 if 语句中打印你想要的数据时,为什么要使用 continue 呢?
name_lst = [
["koala", "1111", "on"],
["cat", "2222", "off"],
["fox", "3333", "on"],
["hin", "4444" "off"]
]
for data in name_lst:
username, password, status = data
if status == "on":
print(f"username: {username}")
print(f"password: {password}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.