We have already seen how to create aNested functions in Python.
If a nested function is returned from a function, the nested function can access the variables defined in the function even if the function is no longer active.
This is a simple counterexample.
def counter():
count = 0
<span style="color:#66d9ef">def</span> <span style="color:#a6e22e">increment</span>():
nonlocal count
count <span style="color:#f92672">=</span> count <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>
<span style="color:#66d9ef">return</span> count
<span style="color:#66d9ef">return</span> increment
increment = counter()
print(increment()) # 1
print(increment()) # 2
print(increment()) # 3
We returnincrement()
Internal functions and still accessiblecount
even ifcounter()
The function has ended.
More python tutorials:
- Introduction to Python
- 在macOS上安装Python 3
- Run Python program
- Python 2 and Python 3
- Basics of using Python
- Python data types
- Python operators
- Python string
- Python boolean
- Python numbers
- Python, accepts input
- Python control statements
- Python list
- Python tuple
- Python set
- Python dictionary
- Python functions
- Python objects
- Python loop
- Python module
- Python class
- Python standard library
- Debug Python
- Python variable scope
- Python, accept parameters from the command line
- Python recursion
- Python nested functions
- Python Lambda function
- Python closure
- Python virtual environment
- Use Python to use GoPro as a remote webcam
- Python, how to create a list from a string
- Python decorator
- Python Docstrings
- Python introspection
- Python notes
- 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 detailed information of a file
- Python, how to check if a file or directory exists
- Python exception
- Python, how to create a directory
- Python, how to create an empty file
- Python, `with` statement
- Python, create a network request
- Python, use `pip` to install third-party software packages
- Python, read file content