⊗pyPmFnFIF 20 of 128 menu

Function in function in Python

In Python, functions can be declared inside other functions. Let's say we have an outer function outer, inside which is a function inner:

def outer(): def inner(): pass

The example above looks simple enough. However, there are often situations when in the body of the function outer, in addition to inner, other operations are performed. To simplify the code, inner could be moved to the outer code block, but this function will only be used once and only inside the function outer. Therefore, moving it outside does not make sense.

Let's look at an example where a list is passed to the outer function. And with the help of the inner function, the numeric element of the list will be raised to a square power. To do this, after the inner function, we declare an empty list res, in which the elements raised to a square in the cycle will accumulate:

def outer(lst): def inner(num): return num ** 2 res = [] for el in lst: res.append(inner(el)) return res

Let's call the outer function, pass it a list parameter, and print the result to the console:

print(outer([2, 3, 5])) # [4, 9, 25]

Write an outer and inner function that, when used together, will capitalize each lowercase element of a list.

The following functions are given:

def func1(num): if num > 0: num += 2 return num def func2(iter): res = [] for el in iter: res.append(func1(el)) return res

Rewrite the code so that func1 is an inner function of func2.

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