Get startedGet started for free

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

This exercise is part of the course

Writing Functions in Python

View Course

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Make print_sum() run 10 times with the run_n_times() decorator
____
def print_sum(a, b):
  print(a + b)
  
print_sum(15, 20)
Edit and Run Code