Unable to understand how function is being called in python

Viewed 99

How is function (square,cube) being stored in operations variable. How function is being called here? How this code actually executes ?

def square(n):
 return n**2

def cube(n): 
 return n**3
operations = [square, cube]
numbers = [2, 1, 3, 4, 7, 11, 18, 29]
for i, n in enumerate(numbers):
      action = operations[i % 2]
      print(f"{action.__name__}({n}):", action(n))

Output:

square(2): 4
cube(1): 1
square(3): 9
cube(4): 64
square(7): 49
cube(11): 1331
square(18): 324
cube(29): 24389
1 Answers

The first part defines the functions square and cube and stores a reference for each function in the operations list.

def square(n):
 return n**2

def cube(n): 
 return n**3
operations = [square, cube]

The second part enumerates and loops through the numbers, using square when i is even, and cube when it's not.

numbers = [2, 1, 3, 4, 7, 11, 18, 29]
for i, n in enumerate(numbers):
      action = operations[i % 2]
      print(f"{action.__name__}({n}):", action(n))

Related