MulaiMulai sekarang secara gratis

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

Latihan ini adalah bagian dari kursus

Writing Functions in Python

Lihat Kursus

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# 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 dan Jalankan Kode