4

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
Usus
  • 89
  • 4

1 Answers1

4

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))

Ahmed Tounsi
  • 1,482
  • 1
  • 14
  • 24
  • I wanna know that, is n**2 is returned to square which is in the operations list at first. And in the second part of the program, how action(n) prints 4 at first? Could you provide any site links to understand it better? – Usus Sep 20 '20 at 08:45
  • 1
    1) action variable has function and has no parameter. 2) i%2 returns 0 for 0,2,4... and 1 for 1,3,5 value of i. 3) This means numbers[0], numbers[2] etc are used for square function, which is operations[0] 4) numbers[1], numbers[3] are used for cube function which is operations[1]. This is the reason, first SQUARE returned then CUBE returned then SQUARE returned then CUBE returned etc., – Abdul Hameed Sep 20 '20 at 09:03