# Рекурсия Python

Функция вPythonможет называть себя. Вот что такое рекурсия. И это может быть очень полезно во многих сценариях.

Обычный способ объяснить рекурсию - использовать факториальное вычисление.

Факториал числа - это число`n`искажено`n-1`, умножается на`n-2`… И так далее, пока не будет набрано число`1`:

``````3! = 3 * 2 * 1 = 6
4! = 4 * 3 * 2 * 1 = 24
5! = 5 * 4 * 3 * 2 * 1 = 120Using recursion we can write a function that calculates the factorial of any number:
def factorial(n):
if n == 1: return 1
return n * factorial(n-1)
print(factorial(3)) #   6
print(factorial(4)) #  24
print(factorial(5)) # 120
If inside the factorial() function you call factorial(n) instead of factorial(n-1), you are going to cause an infinite recursion. Python by default will halt recursions at 1000 calls, and when this limit is reached, you will get a RecursionError error.
Recursion is helpful in many places, and it helps us simplify our code when there’s no other optimal way to do it, so it’s good to know this technique.

More python tutorials:

Introduction to Python

Installing Python 3 on macOS

Running Python programs

Python 2 vs Python 3

The basics of working with Python

Python Data Types

Python Operators

Python Strings

Python Booleans

Python Numbers

Python, Accepting Input

Python Control Statements

Python Lists

Python Tuples

Python Sets

Python Dictionaries

Python Functions

Python Objects

Python Loops

Python Modules

Python Classes

The Python Standard Library

Debugging Python

Python variables scope

Python, accept arguments from command line

Python Recursion

Python Nested Functions

Python Lambda Functions

Python Closures

Python Virtual Environments

Use a GoPro as a remote webcam using Python

Python, how to create a list from a string

Python Decorators

Python Docstrings

Python Introspection

Python Annotations

Python, how to list files and folders in a directory

Python, how to check if a number is odd or even

Python, how to get the details of a file

Python, how to check if a file or directory exists

Python Exceptions

Python, how to create a directory

Python, how to create an empty file

Python, the `with` statement

Python, create a network request

Python, installing 3rd party packages using `pip`

Python, read the content of a file

``````