You could do this, but you probably shouldn’t:
def forn(n):
def new_func(func):
for i in range(n):
func(i)
return func
return new_func
@forn(10)
def f(i):
print(i)
or this:
def forn(n, func)
return [func(i) for i in range(n)]
x = forn(10, lambda x: x**2)
But these are more verbose and less readable than
for i in range(10):
print(i)
or
x = [i**2 for i in range(10)]
As others have said, you’ll do best to just use the built-in tools.
solved Can we Write For loop as a function?