Lesson 8. Functions and recursion
1/16. Enter the functionsRecall that in mathematics the factorial of a number n is defined as
forloop. 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:
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)