Exercise: Parking Kiosk

Write the three functions behind a parking garage's pay kiosk, which turn what drivers type into hours or refuse it with a clear ValueError, price the stay or refuse impossible hours with a KioskError, and keep asking until an answer can be priced, and let pytest check what each one returns, raises and prints.

Journeyman · Python · Updated

By

Riverside Parking Garage's pay kiosk asks every driver one question: how many hours did you park? Drivers type 2, 1.5, two, -3, or nothing at all, and the kiosk must never crash and never charge a wrong fee. You'll write the three functions behind it: one turns the typed text into hours or refuses it with a clear message, one prices the stay or refuses hours that make no sense, and one keeps asking until it gets an answer it can price. The tests check what each function returns, what it raises and what it prints.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-python-parking-kiosk, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:

cd ~/python-course
git clone https://github.com/ask-codey/exercise-python-parking-kiosk.git

Git makes a folder, exercise-python-parking-kiosk, with the exercise code inside. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment, as Virtual Environments and pip explains. On Windows (PowerShell):

python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt

On a Mac (zsh):

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

The prompt starts with (.venv) once the virtual environment is on.

The folder holds:

  • kiosk.py: the three functions, for you to finish. The prices and the KioskError exception at the top are ready to use.
  • day.py: prints a day of answers typed at the kiosk, priced or refused by your functions. Ready to use.
  • pay.py: the kiosk itself, which asks you for the hours. Ready to use.
  • tests/test_kiosk.py: the tests, which call each function and check what comes back. You don't need to change it.
  • requirements.txt and pytest.ini: the package the tests need, and where pytest finds the tests and your code.

A test that checks for an error is written with pytest.raises(ValueError):, and it passes only when the code inside it raises that exception. Testing Edge Cases and Errors teaches it in Module 4; the README says what you need to read the tests.

What to do

Every function in kiosk.py is already declared with its name and parameters, and for now it stops with a NotImplementedError that says Not built yet. The docstring under each one says what it should do, with examples:

def parse_hours(text):
    """Return the hours a driver typed, as a number (a float).

    Spaces before or after the number are fine: float() ignores them.
    When the text isn't a number, raise ValueError with this message, with
    what was typed in single quotes at the end:

        Please type the hours as a number, such as 2 or 1.5, not 'two'.

    parse_hours("2") -> 2.0
    parse_hours(" 1.5 ") -> 1.5
    parse_hours("two") raises ValueError: Please type the hours as a number, such as 2 or 1.5, not 'two'.
    parse_hours("") raises ValueError: Please type the hours as a number, such as 2 or 1.5, not ''.
    """
    raise NotImplementedError("Not built yet.")

In each function, replace the raise NotImplementedError("Not built yet.") line with your own code:

  1. parse_hours(text) returns the typed hours as a float. When the text isn't a number, it raises a ValueError with the kiosk's own message, which ends with what was typed in single quotes.
  2. parking_fee(hours, lost_ticket=False) returns the fee: $4.00 an hour, but never more than $24.00. With lost_ticket=True the fee is $30.00, however long the stay. Negative hours raise a KioskError whose message is Hours can't be negative, but got -3., with the hours at the end.
  3. run_kiosk() asks Hours parked: with input(), and gives the answer to parse_hours, then to parking_fee. When either raises its error, it prints the error's message and asks again. When both work, it prints the fee as Please pay $10.00. and returns it. Its docstring shows a whole conversation: two, then -3, then 2.5.

Catch only the two errors the kiosk expects, ValueError and KioskError, never with a bare except:.

Check your work

Run the tests from the exercise folder, with the virtual environment on:

pytest

At first all 13 tests fail. That's expected: each function you finish turns its tests green. A failing test's message says what it called, what it expected and what came back, for example parking_fee(9) should return 24.0, but it returned 36.0.

To see your functions at work, run python day.py. To use the kiosk the way a driver would, run python pay.py and type two, then -3, then 2.5.

Hints

  • Work an example through by hand first. 9 hours at $4.00 is $36.00, which is over the daily maximum, so the fee is $24.00. Exactly 6 hours is $24.00 too.
  • Let float() find the bad answers. It already raises a ValueError for text that isn't a number. Catch it with except ValueError:, then raise a new ValueError with the kiosk's message. Raising Your Own Exceptions shows the idea.
  • Refuse first, price second. In parking_fee, check for negative hours before anything else, and stop there with raise KioskError(...).
  • Keep asking with while True:. Put the asking, the parsing and the pricing in a try, print the error in the except blocks, and return the fee from the else block, which ends the loop. Handling Errors with try and except shows except ... as error.
  • A test fails and you can't see why? Put a breakpoint in your function and run day.py under the debugger, as Finding Bugs with the Debugger shows, then step and watch the values.

When you're done

Every test is green: pytest's last line says 13 passed. And python day.py prints:

Riverside Parking Garage: today's tickets
'2': $8.00
'1.5': $6.00
'two' refused: Please type the hours as a number, such as 2 or 1.5, not 'two'.
'9': $24.00
'-3' refused: Hours can't be negative, but got -3.0.
' 4 ': $16.00
Lost ticket: $30.00

Now look back at run_kiosk. What would happen to a driver if a typo in parking_fee, such as HOURLY_RAT, were caught by a bare except: instead of your two named ones?

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.

  1. On GitHub, click +, then New repository. Name it (for example exercise-python-parking-kiosk), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-python-parking-kiosk.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-python-parking-kiosk, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

Real programs meet real people, who type everything except what you expected; a program that refuses bad input with a clear message, and keeps going, is one people can trust.

Key terms

Related