Python Python Basics All Together Now Handle Exceptions

William Davis
William Davis
10,070 Points

How would we deal with users asking for a negative amount of tickets (eg: -1 tickets)?

The exception raised is great for users who want to order more tickets than available and for users who write something other than a positive number, but it doesn't work if I say that I want -1 tickets, as the script continues and even adds it to the number of tickets remaining.

How would we deal with this situation?

2 Answers

Steven Parker
Steven Parker
186,665 Points

You can easily add another test & raise similar to the one for excessive tickets, right above or right below the existing one:

        if num_tickets < 1:
            raise ValueError("We cannot sell less than 1 ticket!")

For better efficiency, the second test can be changed to an "elif", since both conditions can't be true at the same time.

Pamela Wallace
Pamela Wallace
2,125 Points

Why doesn't the code below catch this error?

while tickets_remaining >= 1:
Steven Parker
Steven Parker
186,665 Points

There could be plenty "tickets_remaining". A negative order shows up in "num_tickets".