[英]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.