Python Loop for counting backwards (syntax of statement)

Question:

I’m a student that recently began to study Python, i was wondering how could I write a code that when you write a number the program writes all the numbers till 1 in order, ex: input=5
and it has to print 4,3,2,1…. The problem is when it comes to a negative number because i can write a code for those and it could be like:

num=int(input("Insert Input"))
while num > 0:
    print(num)
    num=num-1

Does anyone know how could I stop the counter? Ex. input=-9 -9,-8,-7…..1 I’ve tried everything but I really can’t understand how the mechanic of this loop works. I can’t understand how python works with the variables : for i in range(...) How can I use these parameters to go from negative numbers to positive ones?
The code has to be as easy as possible cause i didn’t do a lot of functions and i want to learn on my own some loops. Ty 🙂

Asked By: Lvcaa

||

Answers:

You can use range() and pass -1 as the step parameter to count backwards.

num = 5
for i in range(num - 1, 0, -1):
    print(i)

#4
#3
#2
#1

If you do not wish to use range, you can still use your while loop, there is no need to break.

while num > 0:
    print(num)
    num -= 1

#5
#4
#3
#2
#1

If you want to pass both negative and positive numbers and count towards 0, we can add an if statement to our step parameter.

for i in range(num, 0, -1 if num > 0 else 1):
    print(i)
Answered By: PacketLoss
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.