Python Forum
why this error occured in recursion
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
why this error occured in recursion
#1
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'
Reply
#2
because when n < 1 your function will not return anything explicitly, so it returns None and thus the error.
Check this visualization tool
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Max recursion depth.... Error MeloB 2 1,839 Feb-16-2022, 05:21 PM
Last Post: MeloB
Bug maximum recursion depth exceeded while calling a Python object error in python3 Prezess 4 3,690 Aug-02-2020, 02:21 PM
Last Post: deanhystad
  Lambda function recursion error DeadlySocks 1 2,011 Apr-13-2020, 05:09 PM
Last Post: deanhystad
  matplotlib recursion error when repeatedly displaying a surface AdeIsHere 0 1,896 Sep-19-2019, 04:36 PM
Last Post: AdeIsHere
  Sorry to bother, I've occured a newbiw question. Ethan4216 2 1,688 Aug-30-2019, 05:49 AM
Last Post: Ethan4216
  'Exception Has occured: UnBoundLocalError' caston 1 2,418 Jun-12-2019, 02:33 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020