A small library

Keep track of which books are on loan.

What to build

A Library class whose methods apply all the rules.

Requirements

  • add TITLE: print added T, or already have T.
  • borrow TITLE: print borrowed T, or not available T if it is on loan, or no such book T.
  • return TITLE: print returned T, or not on loan T, or no such book T.
  • At the end, print On loan: N.

Input

The first line has n. Each of the next n lines is a command. Titles are single words.

Output

One line per command, then the total.

Constraints

n is from 1 to 200.

Example

Input:

4
add Dune
borrow Dune
borrow Dune
return Dune

Output:

added Dune
borrowed Dune
not available Dune
returned Dune
On loan: 0

Why it works

Every rule sits in one method, so the main loop only passes commands along. The dictionary answers both questions, whether the book exists and whether it is out.

Examples

Example 1 · Input
4
add Dune
borrow Dune
borrow Dune
return Dune
Expected output
added Dune
borrowed Dune
not available Dune
returned Dune
On loan: 0
Example 2 · Input
2
borrow Emma
return Emma
Expected output
no such book Emma
no such book Emma
On loan: 0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Keep a dictionary from title to a Book object, or to True when it is on loan.

Hint 2

Decide the order of the checks: does the book exist, and is it on loan?

Hint 3

At the end, count the books that are on loan.

Solution

Show one correct solution (try it yourself first)
class Library:
    def __init__(self):
        self.on_loan = {}

    def add(self, title):
        if title in self.on_loan:
            return f"already have {title}"
        self.on_loan[title] = False
        return f"added {title}"

    def borrow(self, title):
        if title not in self.on_loan:
            return f"no such book {title}"
        if self.on_loan[title]:
            return f"not available {title}"
        self.on_loan[title] = True
        return f"borrowed {title}"

    def return_book(self, title):
        if title not in self.on_loan:
            return f"no such book {title}"
        if not self.on_loan[title]:
            return f"not on loan {title}"
        self.on_loan[title] = False
        return f"returned {title}"

library = Library()
n = int(input())
for _ in range(n):
    command, title = input().split()
    if command == "add":
        print(library.add(title))
    elif command == "borrow":
        print(library.borrow(title))
    else:
        print(library.return_book(title))
print("On loan:", sum(library.on_loan.values()))

Lesson: Classes and objects →