Loops seem to be confusing

Hi there can somebody explain where did 0 1 2 come from?

n = 0
while True:
    if n == 3:
        break
    print(n)
    n = n + 1

0
1
2

Yep.
At the first line you are declaring, that n = 0

So, at the first step of looping, you are printing zero

And only after that you are doing incrementation (n=n+1)

Then the same stuff happens for n = 1…

And welcome to the forum, of course)

Hey, thanks a lot.
So 3 was skipped because break stopped it out, right?

Yeah, this:

is you are saying: if n = 3, it’s time to get rid out of this loop

Also, in general.
Python doesn’t use many parenthesis, brackets and stuff like that.

try to do some research, how to indent your code properly for readability

for example with your code I would do something like

n = 0

while True:
     if n == 3:
          break
    print(n)
    n = n + 1
1 Like

Thanks again. I appreciate your help

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

Got you. Thanks for correction

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.