summaryrefslogtreecommitdiffhomepage
path: root/python.html.markdown
diff options
context:
space:
mode:
authorMohammed Ashour <m.aly.ashour@gmail.com>2023-12-14 19:58:53 +0100
committerGitHub <noreply@github.com>2023-12-14 19:58:53 +0100
commit05aa44a0419b735dcb6d5e63347c1e0d4ba9fc8e (patch)
tree8abd26bb17548cbf851d44a6f8b22e7a5638e4c7 /python.html.markdown
parent58d91b0ba3e5bd1fda571f92bdd69aab5fd0da04 (diff)
[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
Diffstat (limited to 'python.html.markdown')
-rw-r--r--python.html.markdown16
1 files changed, 16 insertions, 0 deletions
diff --git a/python.html.markdown b/python.html.markdown
index 49b46711..967c2bd7 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -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