⊗pyPmFnCl 23 of 128 menu

Closures in Python

By closure we mean a function together with all external variables that are accessible to it.

In Python, most often, when people say "function closure", they don't mean the function itself, but rather its external variables.

Let's say we have the following function outer, which declares a variable i and an inner function inner. In it, one will be added to i. In order for the variable i to work correctly, we add the instruction nonlocal to it:

def outer(): i = 0 def inner(): nonlocal i i += 1 print(i) return inner

Now let's put the external function in the variable res and call it with parentheses:

res = outer() res() # 1

Let's call res several times. After executing the code, the counter i will increase by one each time:

res() # 2 res() # 3 res() # 4

However, there is an important nuance here - each call to the outer function will increase its counter. Let's write the first call to outer to the variable res1, and the second call to the variable res2. Then we'll output them to the console one after another:

res1 = outer() res1() # 1 res1() # 2 res1() # 3 res2 = outer() res2() # 1 res2() # 2 res2() # 3

The following code is given:

def outer(): i = 10 def inner(): nonlocal i i -= 2 print(i) return inner res1 = outer() res1() res1() res2 = outer() res2() res2() res2()

Tell me what will be output to the console.

Make a function that each time it is called will return the next Fibonacci number.

Make a function that will return a random integer in the range, but so that it will not be the same twice in a row.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline