Aan de slagGa gratis aan de slag

Run_n_times()

In the video exercise, I showed you an example of a decorator that takes an argument: run_n_times(). The code for that decorator is repeated below to remind you how it works. Practice different ways of applying the decorator to the function print_sum(). Then I'll show you a funny prank you can play on your co-workers.

def run_n_times(n):
  """Define and return a decorator"""
  def decorator(func):
    def wrapper(*args, **kwargs):
      for i in range(n):
        func(*args, **kwargs)
    return wrapper
  return decorator

Deze oefening maakt deel uit van de cursus

Writing Functions in Python

Cursus bekijken

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# Make print_sum() run 10 times with the run_n_times() decorator
____
def print_sum(a, b):
  print(a + b)
  
print_sum(15, 20)
Code bewerken en uitvoeren