Make program count up when given a negative number in python

Viewed 463

I need to make this code work in this way. When a negative number is give (-3) it should count up -3, -2, -1, 0, Blastoff!
The code only counts down to 0 from a positive number and when a negative number is given, it only prints "Blastoff!"
My initial thought was to change "<" to a ">" in the second function but didn't do anything.
Also, I need to make it in such a way that when I enter 0, it would count up in pairs instead when number 0 is given, it breaks the program as a whole.

Please help, just remember you are talking to a newbie.
This is a home practice exercise and I have tried to do it but cant figure it out, and haven't found anything in YouTube or here to explain the procedure in python.

n = int(input("Please enter a number: "))
def countdown(n):
    if n <= 0:
        print('Blastoff!')
    else:
        print(n)
        countdown(n-1)
countdown(n)

def countup(n):
    for n in range(0, -100000):
        if n >= 0:
            print ( "Blastoff! ")
        else:
            print (n)
            countup (n+1)
countup(n)

def countZero(n):
    if n == 0:
        print ("You hit the magic 0 ")
    else:
        print (n)
        countZero(n+2)
countZero()                
1 Answers

Remove the for loop in countup, and make sure to pass in a negative number.

Note that the range method there is not doing what you expect:

>>> list(range(0, -3))
[]

If its negative you need to flip the start index. If you want zero to be shown then stop at 1:

>>> list(range(-3, 0))
[-3, -2, -1]

>>> list(range(-3, 1))
[-3, -2, -1, 0]

So you could do:

>>> def countup(n):
...     for n in range(n, 1):
...         if n >= 0:
...             print("Blastoff!")
...         else:
...             print(n)
...             
>>> countup(-3)
-3
-2
-1
Blastoff!

If you want to keep it recursive, then you don't need the loop at all:

>>> def countup(n):
...     if n >= 0:
...         print("Blastoff!")
...     else:
...         print(n)
...         countup(n + 1)
...         
>>> countup(-3)
-3
-2
-1
Blastoff!

Bonus If you want one method to handle counting up and counting down, use another if/ else statement:

>>> def blastoff(n):
...     if n == 0:
...         print("Blastoff!")
...     else:
...         print(n)
...         if n > 0:
...             blastoff(n - 1)
...         else:
...             blastoff(n + 1)
... 
>>> blastoff(3)
3
2
1
Blastoff!
>>> blastoff(-3)
-3
-2
-1
Blastoff!
Related