Python Forum

Full Version: why this error occured in recursion
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
def fact(n):
	if n<= 1:
  		print(1) #if i use "return 1" here then no error but when i use here print(1) why the error occurred                                                                                 
	else:
		return n*fact(n-1)

f=fact(3)
print(f)
Error:
F:\Python Program>test.py 1 Traceback (most recent call last): File "F:\Python Program\test.py", line 7, in <module> f=fact(3) File "F:\Python Program\test.py", line 5, in fact return n*fact(n-1) File "F:\Python Program\test.py", line 5, in fact return n*fact(n-1) TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
because when n < 1 your function will not return anything explicitly, so it returns None and thus the error.
Check this visualization tool