Context Managers

Lab Python Advanced 30 points

Write a class Indent usable with with: entering increases a shared indent level by 2 spaces, exiting decreases it. Inside nested blocks print lines with the current indentation. Read a nesting depth d and print level K at each depth 1..d, then back to 0.

Input

One integer.

Output

d + 1 lines.

Example

Input

3

Output

  level 1
    level 2
      level 3
back to 0
Sample input available Sample output available
Editor
Python

Hints

with calls __enter__ at the start and __exit__ at the end, even if an error occurs.

Solution explanation

Context managers guarantee cleanup — files, locks and database transactions all use them.

Show solution
class Indent:
    level = 0

    def __enter__(self):
        Indent.level += 1
        return self

    def __exit__(self, exc_type, exc, tb):
        Indent.level -= 1
        return False


def show(text):
    print("  " * Indent.level + text)


def nest(depth):
    if depth == 0:
        return
    with Indent():
        show(f"level {Indent.level}")
        nest(depth - 1)


nest(int(input()))
show(f"back to {Indent.level}")
Output
Answer
HOME LEARN COMMUNITY DASHBOARD