Python Forum
While statement explanation - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: While statement explanation (/thread-29402.html)



While statement explanation - alkhufu2 - Aug-31-2020

I am new to Python. I get while and for loops pretty well so far but I DO NOT understand the output of this code. Please explain this. I would most appreciate it.
n = 3
while n > 0:
    print(n + 1, end=' ')
    n -= 1
else:
    print(n)
Output:
4 3 2 0

Thank you for any help!


RE: While statement explanation - nilamo - Aug-31-2020

Let's walk through the code, line by line, and keep track of what n is.

n = 3                       # 3
while n > 0:                # 3
    print(n + 1, end=' ')   # 3 (print 4)
    n -= 1                  # 2

while n > 0:                # 2
    print(n + 1, end=' ')   # 2 (print 3)
    n -= 1                  # 1

while n > 0:                # 1
    print(n + 1, end=' ')   # 1 (print 2)
    n -= 1                  # 0

else:
    print(n)                # 0



RE: While statement explanation - deanhystad - Sep-01-2020

What is it you don't understand? That the numbers printed count down from 4 instead of 3, or that they all appear on the same line?

The numbers start at 4 and count down to 1 because you are printing n+1, not n. The value for n starts at 3 and it ends at 0, so the output starts at 3+1 and ends at 0+1. nilamo covers this very well.

The numbers are all printed on the same line because you replaced the "end" string. Normally the print command end = '\n' which is a new line, but you replaced this with a space. So when you print it just prints the value of n+1 and a space instead of the value of n+1 and a newline character.


RE: While statement explanation - alkhufu2 - Sep-02-2020

Thank you all for the response. It was the output itself (the integers). Nilamo described it perfectly. I see where the breakdown in understanding the way it executed past the first iteration.