-2

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 use the break command in order to stop negative numbers for writing them till 1? Ex. input=-9 -9,-8,-7.....1 Obviously it will be necessary to insert an if condition to verify if the entered number is negative or positive. 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 :)

DarrylG
  • 14,084
  • 2
  • 15
  • 21
Lvcaa
  • 1
  • 6

1 Answers1

1

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)
PacketLoss
  • 5,234
  • 1
  • 8
  • 26
  • It seems a perfect solution, the problem is that when i write like -3 nothing happens, like python does not recognize the negative number, what should i do? I tried both solutions – Lvcaa Oct 23 '21 at 11:24
  • @Lvcaa Updated answer to include negatives. – PacketLoss Oct 23 '21 at 11:27
  • ok now it works, last question I promise, what if I want it to count to 1 and not 0? Ty so much for the help – Lvcaa Oct 23 '21 at 11:29
  • @Lvcaa Change the second parameter to `range()` this is the number it will stop at. `range(start, stop, step)` – PacketLoss Oct 23 '21 at 11:30