Factorial in Python - recursive


fact rec en

def silnia(n):
    if n > 1:
        return n * silnia(n-1)
        return 1
n = int(input('n = '))
print(n, '! =', silnia(n))



 In lines 0d 1 to 5 we define the factorial function. The body of the function is located under the header and is written with mandatory indentation.

 In line 2 we check if n is greater than 1 - block (3) of the algorithm. If so, in line 3, written with additional indentation, we specify the result of the function as n multiplied by the value of the factorial function (the same factorial function we are currently defining) for n minus 1 (4). At this point, the factorial function calls itself. We call this a recursive function. If n is not greater than 1, then in line 5 we set the result of the function equal to 1 (recursion termination condition) - block (5).

 In the 6th line of the program, using the input() function, we read an integer (int type) from the standard input (keyboard), which we immediately store in the variable n - block (2) of the algorithm.

 In line 7, using the standard print() function, we print the result of the algorithm - block (6) by calling the factorial() function.