Start learning free

LESSON 662 OF 673 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Ticket Booking in Python: Raising ValueError From a Method

Practice O(1) Read the full explanation

You build the class Event. An event has a name and a number of free seats.

Implement the class Event:

  • Event(name, seats) creates an event with seats free seats.
  • name is a field that any code can read.
  • The seats left are a private field, as in the Access Modifiers lesson.
  • book(n) books n seats and returns how many are left.

A booking can fail. Then book raises an error with a message, and nothing changes.

  • When n is 0 or less, the message is "invalid number".
  • When n is more than the seats left, the message is "sold out".

Raise the errors the way the Errors and Exceptions lesson does:

  • Python: raise ValueError("sold out").
  • JavaScript and TypeScript: throw new Error("sold out").
  • Java, Kotlin and Scala: throw an IllegalArgumentException.
  • C#: throw an ArgumentException. The method is named Book.
  • C++: throw an invalid_argument.
  • Swift: throw a BookingError. The starter code declares it.

The input lists the bookings of each event, in order. The tests call book and catch its errors. For each event they print its name. Then they print one line per booking:

  • booked 2, 3 left when 2 seats were booked and 3 are left.
  • error: sold out when the booking failed with the message "sold out".

 

Example 1:

Input:
    Event("Concert", 5)
    book(2)
    book(4)
    book(3)
Output:
Concert
booked 2, 3 left
error: sold out
booked 3, 0 left

Explanation:
2 seats are booked, so 3 are left.
4 is more than 3, so the error is "sold out".
The failed booking changed nothing.
So book(3) gets the last 3 seats.

Example 2:

Input:
    Event("Play", 4)
    book(-1)
    book(4)
Output:
Play
error: invalid number
booked 4, 0 left

Explanation:
No one can book -1 seats.
book(4) then takes all 4 seats.

Example 3:

Input:
    Event("Match", 0)
    book(0)
Output:
Match
error: invalid number

Explanation:
The event has no seats at all.
Booking 0 seats is never valid, so the error is "invalid number".

 

Constraints:

  • Each event has 0 to 100,000 seats.
  • Each n is a whole number from -100 to 100,000.
  • An event gets 1 to 1,000 bookings.
  • Event names are one word of English letters.
STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

    Ticket Booking in Python, explained

    Problem overview

    The class Event has a name and a number of free seats. Event(name, seats) creates it, name is a field any code can read, and the seats left are a private field. book(n) books n seats and returns how many are left.

    A booking can fail, and then book raises an error and changes nothing:

    • When n is 0 or less, the message is "invalid number".
    • When n is more than the seats left, the message is "sold out".

    In Python the error is a ValueError. For Event("Concert", 5), booking 2 leaves 3. Booking 4 then fails with sold out, and because that failure changed nothing, booking 3 afterwards takes the last seats and leaves 0.

    Approach

    The method has three outcomes, so it works best as a short chain of checks followed by the real work. Check for the invalid number first, then for too many seats, and only when both checks pass change the seat count. Raising an error stops the method on the spot, so the line that subtracts the seats is never reached after a failure. That is how "nothing changes" comes for free: the order of the lines does the job.

    The order of the two checks matters in one case. If n is 0 and the event has no seats, "0 is more than 0" is false, but "0 or less" is true, so the answer is invalid number. Checking n <= 0 first gives the result the examples show for an event with 0 seats and a booking of 0.

    Step by step

    1. In __init__, store the name in self.name, a public field.
    2. Store seats in self._seats_left. The underscore says only the class's own methods change it.
    3. In book, write an if for n being 0 or less, and raise a ValueError with the message "invalid number".
    4. Write a second if for n being more than self._seats_left, and raise a ValueError with the message "sold out".
    5. Now the booking can go ahead: subtract n from self._seats_left and return self._seats_left.

    The solution in Python

    class Event:
        def __init__(self, name, seats):
            self.name = name
            self._seats_left = seats
    
        def book(self, n):
            if n <= 0:
                raise ValueError("invalid number")
            if n > self._seats_left:
                raise ValueError("sold out")
            self._seats_left -= n
            return self._seats_left

    Details worth knowing

    The second if is not an elif, and it doesn't need to be: when the first one raises, the method has already ended. Both styles behave the same here.

    The caller catches the error with try and except ValueError as err, and printing err shows the message. An error that nobody catches stops the program.

    The seat count is private only by convention. The underscore asks other code to stay out; Python would still let it read event._seats_left.

    Using the class

    def run(name, seats, bookings):
        e = Event(name, seats)
        print(e.name)
        for n in bookings:
            try:
                print(f"booked {{n}}, {{e.book(n)}} left")
            except ValueError as err:
                print("error:", err)
    
    run("Concert", 5, [2, 4, 3])
    run("Play", 4, [-1, 4])
    run("Match", 0, [0])
    Concert
    booked 2, 3 left
    error: sold out
    booked 3, 0 left
    Play
    error: invalid number
    booked 4, 0 left
    Match
    error: invalid number

    Edge cases and common mistakes

    • Subtracting before checking. A failed booking would still lower the seat count. Do the checks first.
    • Using < where <= is needed. The check for an invalid number is n <= 0, because 0 seats is never a valid booking. The check for too many seats is n > self._seats_left, because booking exactly the seats left is fine and leaves 0.
    • Returning instead of raising. Returning a text like "sold out" mixes errors with seat counts. Raise the error.
    • Swapping the messages. The two messages are part of the lesson's output, so spell them exactly.
    • Booking more than once after a failure. A failed call does not use up the seats, so the next booking sees the same count.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free