samedi 21 novembre 2020

Continue without break? What happens in this code?

What is a loop doing when an if statement has a continue statement, but no break? And what about the code in the loop after that?

For example:

h = [1, 1, 0, 1, 0]

for element in h:
    if element == 1:
        print(element)
        continue
    print('My name')

Gives:

1
1
My name
1
My name

But I think it should be:

1
My name
1
My name
1
My name

Because the for loop runs print('My name') when element is 1 and not when it's 0. Here is all what I get this code should do: "Run element and print('My name') when element is 1, and else do nothing."

And also, what happens if there are more of this type of if statement in the for loop?

P.S. I wish the explanation of why this happens, and not another code that gives the output which I want.

Aucun commentaire:

Enregistrer un commentaire