Douglas Hofstadter's Pulitzer-prize-winning book, Gdel, Escher, Bach, poses the following mathematical puzzle:Pick a positive integer n as the start.If n is even, divide it by 2.If n is odd, multiply it by 3 and add 1.Continue this process until n is 1.The number n will travel up and down but eventually end at 1 (at  least for all numbers that have ever been tried -- nobody has ever  proved that the sequence will terminate). Analogously, hailstone  travels up and down in the atmosphere before eventually landing on  earth.The sequence of values of n is often called a Hailstone sequence,  because hailstones also travel up and down in the atmosphere before  falling to earth.Does it make sense to implement using recursion? I wrote some bad solution below. Please correct me.def hailstone(n):    if(n<0):        print(Invalid input)        return     if(n==1):        print(1)        return     if(n%2 == 0):        print(n)        hailstone(n/2)        return    if(n%2==1):        print(n)        hailstone((n*3) + 1)        returnHow do I move the n<0 condition to the right place?
hailstone sequence using recursion in python
python;programming challenge;recursion;collatz sequence
Your code is a bit awkward, mostly due to:Repetition;Repetition; andDoesn't follow PEP-0008 (specifically, e.g. if(n<0): should be if n < 0:. A few comments:def hailstone(n):    if(n<0):        print(Invalid input) # should be an exception        return # don't need explicit return[ None]    # what if n == 0?    if(n==1):        print(1) # same as print(n)        return # see above     if(n%2 == 0): # n == 0 comes here and loops indefinitely        print(n) # repeat        hailstone(n/2)        return # repeat    if(n%2==1): # should just be else        print(n) # repeat        hailstone((n*3) + 1)        return # repeatAn alternative, moving all the print(n) to the top and all the return (implicitly) to the bottom, would be:def hailstone(n):    Print the terms of the 'hailstone sequence' from n to 1.    assert n > 0    print(n)    if n % 2 == 0:        hailstone(n / 2)     elif n > 1:        hailstone((n * 3) + 1)