Home > Enterprise >  Why am I getting nonetype when calling a function within a function in Python?
Why am I getting nonetype when calling a function within a function in Python?

Time:01-10

I'm tying to do a Collatz sequence with python code. I'm supposed to make a function that, given n, calculates the next number in the sequence. I want the next function "write" to print each number within the sequence.

My code so far:

def collatz(n):
while n != 1:
    if n % 2 == 0:
        n = n/2
        return write(n)
    else:
        n = 3*n 1
        return write(n)
def write(n):
    print(n)
    print(collatz(n))

write(6)

It gives me the right sequence, which should be 6, 3,10,5,16,8,4,2,1, but also gives me 9 "nones". I'm new to programming, it should probably be something easy, but I can't figure out what.

CodePudding user response:

write() is a function that executes two print() statements, and then implicitly returns None (since there are no return statements in the function).

You can simplify the code by using print() directly in collatz(), and eliminating the mutual recursion:

def collatz(n):
    while n != 1:
        if n % 2 == 0:
            n = n//2
            print(n)
        else:
            n = 3*n 1
            print(n)

collatz(6)

CodePudding user response:

#Here this will help you understand. When n becomes 1, the while loop is not #excecuted, collatz does not return

def write(n): print(n) result = collatz(n) if result != None:

    print(collatz(n))
  •  Tags:  
  • Related