Help with a for loop quiz question

Hello there, I am currently a novice at python and am studying for the pcep entry level certification but, I am having difficulty understanding the output of the following code:

i included a picture showing the code in question. The answer is explained but it doesn’t click for me. Why does the variable get incremented twice inside the else: branch?

i understand it getting incremented once inside the else branch but I do not understand why it is incremented another time after.

I hope this makes sense and I appreciate anyone who responds back. Thank you

Please don’t post pictures of code. We don’t edit code with Photoshop, and pictures discriminate against the blind and visually impaired who are using a screen reader.

Yes, blind programmers exist.

Please post the code as text, copy and paste it (don’t retype it from memory) and place it between “code fences” so the indentation is not lost. In the website post entry widget, you can use the </> button or you can type three backticks on a line of their own like this:

```
code goes here
```

That way we can copy and paste the code, if we need to run it.

Thank you.

2 Likes

The else on the for loop here is actually a complete red herring. It’s going to be executed any time the inner loop doesn’t break, which - since there is no break statement in it at all - is inevitable. So the loop is equivalent to this:

others = -1
for i in [1, 2]:
    for j in [1]:
        if i == j:
            others += 1 # first increment
    others += 1 # second increment
print(others)

Since that second increment happens once for each pass through the outer loop, it will happen twice, which should be obvious if we remove most of the code:

for i in [1, 2]:
    others += 1

I think the description may be misleading you a little; when it says that the variable is “incremented twice”, what it means is that Python will hit that line of code twice - once when i is 1, and once when i is 2. Each time, others will get incremented (by one).

Hope that helps!

2 Likes

Hi Chris,

Yes this really did help me, thank you so much I really appreciate it! :blush: :smile:

Excellent. Keep on asking questions every time you’re confused, and before long, you’ll be answering questions too :slight_smile:

2 Likes