の関数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