Python Forum
factorial using recursive function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
factorial using recursive function
#1
Hello,
I am practicing on factorial using Recursive function. I am facing an issue here. Kindly correct me.

'''Recursive Function'''
def factorial(n):
    if n == 0:
        result = 1
    else:
        result = n * factorial(n - 1)
    print("the factorial of {} is {}".format(n, result))
    return result
factorial = factorial(5)
Output:
the factorial of 0 is 1 the factorial of 1 is 1 the factorial of 2 is 2 the factorial of 3 is 6 the factorial of 4 is 24 the factorial of 5 is 120 120
Sorry, I got it, I forgot to give factorial while calling. Once added, it is resolved. I have another question please. once it comes to result = n * factorial(n - 1), isn't it that, it should go to def factorial(n): again (the first line), why is it printing print("the factorial of {} is {}".format(n, result)). I hope you understand what I am trying to ask. What I meant is, under else statement, since it is factorial(n - 1), it is supposed to go function definition, why is it printing the next statement called print ("the factorial of {} is {}".format(n, result))
Reply
#2
your code
'''Recursive Function'''
def factorial(n):
    if n == 0:
        result = 1
    else:
        result = n * factorial(n - 1)
    print("the factorial of {} is {}".format(n, result))
    return result
factorial(5)
, provided here works fine for me
Output:
the factorial of 0 is 1 the factorial of 1 is 1 the factorial of 2 is 2 the factorial of 3 is 6 the factorial of 4 is 24 the factorial of 5 is 120
however, your traceback suggest you have following line in the code you run
    factorial(n) == 1
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
#3
Hi Buran,
I updated the post, it is working fine, but I have a new question, kindly look at it.
Reply
#4
your initial code was fine and working. You were running different code, with following line factorial(n) == 1 as suggested by the traceback, which is now removed from your post!

Error:
Traceback (most recent call last): File "C:/Users/spali/PycharmProjects/BeginnerLife/RealPractice/practice.py", line 3522, in <module> factorial(5) File "C:/Users/spali/PycharmProjects/BeginnerLife/RealPractice/practice.py", line 3519, in factorial result = n * factorial(n - 1) File "C:/Users/spali/PycharmProjects/BeginnerLife/RealPractice/practice.py", line 3519, in factorial result = n * factorial(n - 1) File "C:/Users/spali/PycharmProjects/BeginnerLife/RealPractice/practice.py", line 3519, in factorial result = n * factorial(n - 1) [Previous line repeated 2 more times] File "C:/Users/spali/PycharmProjects/BeginnerLife/RealPractice/practice.py", line 3517, in factorial factorial(n) == 1 File "C:/Users/spali/PycharmProjects/BeginnerLife/RealPractice/practice.py", line 3517, in factorial factorial(n) == 1 File "C:/Users/spali/PycharmProjects/BeginnerLife/RealPractice/practice.py", line 3517, in factorial factorial(n) == 1 [Previous line repeated 990 more times] File "C:/Users/spali/PycharmProjects/BeginnerLife/RealPractice/practice.py", line 3516, in factorial if n == 0: RecursionError: maximum recursion depth exceeded in comparison
your changes now are (i) BAD - with your line factorial = factorial(5) now name factorial has value of 5! and the function is no longer available to you (you overwrite the name factorial and (ii) the output show that you have more code, i.e. print(factorial) in order to produce 120 as last line of output.

As to your question - first time when it will reach line 7 print("the factorial of {} is {}".format(n, result)) is wehn n==0, that is why the order is 0 to 5, not the other way around.

I guess you can use this site to visualise the execution and get better understanding what's going on http://www.pythontutor.com/visualize.html#mode=edit
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
#5
This might be helpful as it ha line numbers

'''Recursive Function'''                       
def factorial(n):                                       #line 1
    if n == 0:                                          #line 2
        result = 1                                      #line 3
    else:                                               #line 4
        result = n * factorial(n - 1)                   #line 5
    print("the factorial of {} is {}".format(n, result))#line 6
    return result                                       #line 7
factorial = factorial(5)                                #line 8
print(factorial)                                        #line 9
my question is, in line 5, when it is calling factorial(n - 1), isn't it supposed to go to line 1? why is it printing the statement under line 6. Isn't it how it works? If it is coming to line 6, why is it not going to line 7?
Reply
#6
you are confused, run your code here http://www.pythontutor.com/visualize.html#mode=edit
you will see how the execution goes
and fix the problem with factorial = factorial(5)
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
#7
(Aug-25-2020, 02:29 PM)spalisetty06 Wrote: Hi Buran,
I updated the post, it is working fine, but I have a new question, kindly look at it.

Thank You Buran for the elongated reply. Thanks again, but this code is working perfectly.

def factorial(n):                                       #line 1
    if n == 0:                                          #line 2
        result = 1                                      #line 3
    else:                                               #line 4
        result = n * factorial(n - 1)                   #line 5
    print("the factorial of {} is {}".format(n, result))#line 6
    return result                                       #line 7
factorial = factorial(5)                                #line 8
print(factorial)    
my question is, in line 5, when it is calling factorial(n - 1), isn't it supposed to go to line 1? why is it printing the statement under line 6. Isn't it how it works? If it is coming to line 6, why is it not going to line 7?
Reply
#8
don't add line numbers as comments, it;s confusing. using python` tags will show line numbers
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
#9
(Aug-25-2020, 02:45 PM)spalisetty06 Wrote: Thank You Buran for the elongated reply. Thanks again, but this code is working perfectly.
Wall Wall Wall Wall Wall Wall Wall Wall Wall Wall
no, it's not. the function is OK (and was OK - you were running different code!). The problem is line 8.
try
def factorial(n):                                       
    if n == 0:                                          
        result = 1                                      
    else:                                               
        result = n * factorial(n - 1)                   
    print("the factorial of {} is {}".format(n, result))
    return result                                       
factorial = factorial(5)                                
print(factorial)
# NOW calculate factorial of let's say 4
print(factorial(4))
the result

Error:
the factorial of 0 is 1 the factorial of 1 is 1 the factorial of 2 is 2 the factorial of 3 is 6 the factorial of 4 is 24 the factorial of 5 is 120 120 Traceback (most recent call last): File "/home/boyan/sandbox2/forum.py", line 11, in <module> print(factorial(4)) TypeError: 'int' object is not callable
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
#10
(Aug-25-2020, 02:45 PM)spalisetty06 Wrote: my question is, in line 5, when it is calling factorial(n - 1), isn't it supposed to go to line 1? why is it printing the statement under line 6. Isn't it how it works? If it is coming to line 6, why is it not going to line 7?
How many times should I tell you to run the code on the site I posted twice in order to SEE how the execution goes?
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
  with open context inside of a recursive function billykid999 1 574 May-23-2023, 02:37 AM
Last Post: deanhystad
  Why recursive function consumes more of processing time than loops? M83Linux 9 4,225 May-20-2021, 01:52 PM
Last Post: DeaD_EyE
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,356 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  Execution of Another Recursive Function muzikman 5 3,002 Dec-04-2020, 08:13 PM
Last Post: snippsat
  Don't Understand Recursive Function muzikman 9 3,668 Dec-03-2020, 05:10 PM
Last Post: muzikman
  list call problem in generator function using iteration and recursive calls postta 1 1,895 Oct-24-2020, 09:33 PM
Last Post: bowlofred
  Comparing recursion and loops using two scripts (basic factorial) Drone4four 3 2,237 Oct-11-2020, 06:48 PM
Last Post: deanhystad
  Python factorial code timebrahimy 4 67,853 Sep-27-2020, 12:23 AM
Last Post: timebrahimy
  Recursive function returns None, when True is expected akar 0 3,386 Sep-07-2020, 07:58 PM
Last Post: akar
  factorial, repeating Aldiyar 4 2,791 Sep-01-2020, 05:22 PM
Last Post: DPaul

Forum Jump:

User Panel Messages

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