Search code examples
pythonfor-loopbreak

New to Python; trouble understanding the output of a for loop statement


With an input of

6

And the code:

stop = int(input())
result = 0
for n in range(10):
    result += n + 2
    if result > stop:
        break
    print(n)
print(result)

The result is:

0
1
9

I'm still pretty new to Python and coding in general. I don't know if I'm going down the right path in trying to "translate" the code in my head into something more digestible? Here's how I read it:

We start with 0. We assign the variable n, and there are 10 n in the range. We take the result variable, and add itself + n + 2. Itself is 0, n is 0, so result becomes 2. Since the variable result is less than the input, which is 6, we print n, which is 0. So that part I get.

The next output is 1. I get that because it's the next n in range. And result then increases to n + n + 2, which would be 2 + 2 + 2. So we're at six, now. The output being 0, 1, I get. The next one I feel like should be 2? But it's 9. Why? Where does this 9 come from?


Solution

  • At each step of the loop result increases by n+2, at each step n increases by 1

    Step 0
    result = 0
    
    Step 1
    n = 0
    result = 0+(0+2) = 2
    -> 0 is printed
    
    Step 2
    n = 1
    result = 2+(1+2) = 5
    -> 1 is printed 
    
    Step 3
    n = 2
    result = 5+(2+2) = 9
    result is greater than 6: loops break
    
    -> 9 is printed