-1

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())))
quamrana
  • 37,849
  • 12
  • 53
  • 71
Pingu
  • 3
  • 1

1 Answers1

0

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

KrabbyPatty
  • 312
  • 1
  • 2
  • 9
  • Okk so putting it in little terms it's like a mini loop, cool – Pingu Mar 14 '22 at 19:47
  • @Pingu: In fact, it's how loops are done in functional programming. – Fred Larson Mar 14 '22 at 19:48
  • @Pingu This might be beyond the scope of what you're looking for, but you should be careful with recursive methods. It's easier to end up with an infinite loop if you haven't taken care of the base case. – KrabbyPatty Mar 14 '22 at 19:50
  • 1
    @KrabbyPatty: Also, there's a risk of crashing the program due to excessive stack depth even with properly limited recursion, especially in languages that don't have tail call optimization (such as CPython). – Fred Larson Mar 14 '22 at 19:53