Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

print(fract(int(input())))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading