python while loop with continue statement

Question:

I am trying to print user name and pw using "while loop" and only want to print the user status which is "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

The expect result should be:

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

However, I only got following result.

username: koala
password: 1111
Asked By: AA_SS

||

Answers:

the indentation is not good and it should be status_lst[i] == "off" not "cat" and you’ve created an infinite loop since when you continue you dont increment here is the correct code :

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
    
Answered By: Youtech code

Why use continue when you could just print data you want within the if statement?

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}")
Answered By: OneCricketeer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.