Advanced functions and decorators · 11 / 15 Exercise Medium

Independent counters

Objective

Create a Python program that uses a closure with nonlocal to have several counters that do not get mixed up.

Instructions

  • Define def create_counter(), which has a variable count = 0 and an inner function next_value() that, with nonlocal, adds 1 to count and returns it. create_counter returns next_value.
  • Create two independent counters: a and b.
  • Read a line with letters a or b separated by spaces. For each letter, call the corresponding counter.
  • Show on one line the values obtained, in the same order and separated by spaces.
Input
a a b a b
Output
1 2 1 3 2

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise