Home > Back-end >  Python while loop query
Python while loop query

Time:08-09

I need a little help understanding this piece of code, the result generated by the code is: 4 3 2 0 Why is 1 not being printed? Thanks in advance. here is the code:

n = 3

while n > 0:
    print(n   1, end = " ")
    n -= 1
else:
    print(n, end = "")

CodePudding user response:

n=3 -> prints n 1 i.e. 4
n-1 = 2
n=2 -> prints 3
n-1 = 1
n=1 -> prints 2
n-1 = 0
n=0 -> goes to else statement as while condition is not satisfied. prints 0

CodePudding user response:

It's because you print n 1 every time in the loop, then outside the loop you print n. If you print n 1 the output will be 4 3 2 1:

n = 3
while n > 0:
    print(n   1, end = " ")
    n -= 1
else:
    print(n   1, end = "")
  • Related