[python/en] adding an example for closures in python where we use the nonlocal … (#4033)

* adding an example for closures in python where we use the `nonlocal` keyword 

Adding an example for the case of nested functions with closure scopes, when we use the python 3s keyword 'nonlocal' to point to the variables in the outer functions

* Formatting Comments
This commit is contained in:
Mohammed Ashour 2023-12-14 19:58:53 +01:00 committed by GitHub
parent 58d91b0ba3
commit 05aa44a041
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -655,6 +655,22 @@ def create_adder(x):
add_10 = create_adder(10)
add_10(3) # => 13
# Closures in nested functions:
# We can use the nonlocal keyword to work with variables in nested scope which shouldn't be declared in the inner functions.
def create_avg():
total = 0
count = 0
def avg(n):
nonlocal total, count
total += n
count += 1
return total/count
return avg
avg = create_avg()
avg(3) # => 3.0
avg(5) # (3+5)/2 => 4.0
avg(7) # (8+7)/2 => 5.0
# There are also anonymous functions
(lambda x: x > 2)(3) # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5