Functions and recursion - Learn Python 3 - Snakify

Lesson 8. Functions and recursion




1/16. Enter the functions

Recall that in mathematics the factorial of a number n is defined as n! = 1 ⋅ 2 ⋅ ... ⋅ n (as the product of all integer numbers from 1 to n). For example, 5! = 1 ⋅ 2 ⋅ 3 ⋅ 4 ⋅ 5 = 120. It is clear that factorial is easy to calculate, using a for loop. Imagine that we need in our program to calculate the factorial of various numbers several times (or in different places of code). Of course, you can write the calculation of the factorial once and then using Copy-Paste to insert it wherever you need it:

Instructions

Click "Run" to see what happens in output!

However, if we make a mistake in the initial code, this erroneous code will appear in all the places where we've copied the computation of factorial. Moreover, the code is longer than it could be. To avoid re-writing the same logic in programming languages the functions were invented.
# compute 3!
res = 1
for i in range(1, 4):
    res *= i
print(res)

# compute 5!
res = 1
for i in range(1, 6):
    res *= i
print(res)
Advertising by Google, may be based on your interests