[SOLVED] Who can explain how this code is not an error?


I was making some exercise to train myself and the exercise asked me to do a program that calculates fractals, very simple, i’ve done in about 1-2 minutes and it work, but looking at his solution it return x multiplicated by the function itself? how does this run? I know maybe it’s a stupid question but i think it might be useful.

def fract(x):
    if x == 0:
        return 1
    return x * fract(x - 1)



Here’s a walk through of whats going on.

First, you call fract(int(input())). The input method gets a response from the user and parses that to an int. and then calls fract on that int.

Say we enter 3. So our print statement evaluates to fract(3).

fract(3) returns 3 * fract(2)
fract(2) is called and that returns 2 * fract(1)
fract(1) is called and that returns 1

So putting it altogether and substituting function calls for what they return we get fract(3) returns 3 * (2 * (1)).

Answered By – KrabbyPatty

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *