Home > Blockchain >  Why does it not work when I define the range of my while loop with a variable?
Why does it not work when I define the range of my while loop with a variable?

Time:11-15

I'm a complete novice at python and am trying to list the first n positive numbers, where n is an inputted value. E.g. when n=5, I want to output 5, 4, 3, 2 and 1.

This is my code which doesn't work:

n= int(input("Please enter a number: "))
i=0
while i<n:
    print(n)
    n=n-1
    i=i 1  

I know I can answer the question with this code:

n= int(input("Please enter a number: "))
i=n
while i>0:
    print(i)
    i=i-1

but would like to understand why what I tried at the beginning is not working.

CodePudding user response:

You are decrementing the number and incrementing the counter at the same time.

For example:

n i i<n
5 0 True
4 1 True
3 2 True
2 3 False

The loop exits once False is encountered. To solve this you need to only increment i and use print(n-i), keep the i<n comparison, and remove the 'n=n-1' line

n= int(input("Please enter a number: "))
i=0
while i<n:
    print(n-i)
    i=i 1  

CodePudding user response:

Because, you are decreasing n and increasing i, so at some point the while condition will not satisfy anymore, it has got nothing to do with python.

  • Related