From 05aa44a0419b735dcb6d5e63347c1e0d4ba9fc8e Mon Sep 17 00:00:00 2001 From: Mohammed Ashour Date: Thu, 14 Dec 2023 19:58:53 +0100 Subject: =?UTF-8?q?[python/en]=20adding=20an=20example=20for=20closures=20?= =?UTF-8?q?in=20python=20where=20we=20use=20the=20`nonlocal`=20=E2=80=A6?= =?UTF-8?q?=20(#4033)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 --- python.html.markdown | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'python.html.markdown') 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 -- cgit v1.2.3