Search code examples
pythonfactorial

Python: return dont work


I write this code and I have a problem with return.

def factorial(n):
  if n == 0:
    return 1
  else:
    recurse = factorial(n - 1)
    result = n * recurse
    return result
factorial(3)

When I run it I have that output:

Process finished with exit code 0

And thats it all but when i try it with print i have someting extra:

code:

def factorial(n):
  if n == 0:
    print ("1")
  else:
    recurse = factorial(n - 1)
    result = n * recurse
    print(result)
factorial(3)

Output:

Traceback (most recent call last):
1
Traceback (most recent call last):
  File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 16, in <module>
    factorial(3)
  File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 13, in factorial
    recurse = factorial(n - 1)
  File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 13, in factorial
    recurse = factorial(n - 1)
  File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 14, in factorial
    result = n * recurse
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

Process finished with exit code 1

My question is - why when I try run that with return I don't see anything and what about second code with print?

Maybe my question or issues is stupid, but humans learn from their mistakes


Solution

  • In your second version you don't return anything when n == 0, you just print 1. As a result, the function returns None, which you can't multiply.

    The first version is correct, but if you want to see the result you have to write:

    print(factorial(3))
    

    For reference, this is your code in its entirety.

    def factorial(n):
      if n == 0:
        return 1
      else:
        recurse = factorial(n - 1)
        result = n * recurse
        return result
    
    print(factorial(3))