Create app which handle parking places using python

Hello guys and girls.😀 Hope that you're fine! Ready for this day of script! Yes? Good! So, don't waste our time. Let's talk about today script.

An application to handle parking places?

context.jpg

When I go shopping at the supermarket (although it is not always the case), I am fascinated by the way parking keeps cars. So I said to myself: why not write together a little script that allows you to simply manage a parking lot. In this script, let's reduce the number of available parking spaces (12 places). By the way, it's necessary to be familiar with some knowledges such as:

  • loop
  • dictionaries
  • lists
  • exceptions

Well, now let's get down to business ...

Script context

What we want firstly is that when a driver want to park his car in parking, the program gives to driver a ticket which indicate where he must park. It will also be necessary to know the places available and unavailable and sometimes the number of cars parked by the caretaker. So, let's go!

code.jpg

Start by create a folder called parking.py.

All our script will be write in this file.

Let's start by define our variables.

from random import randint

# let's define variables
total_parking_place = 12 # initial parking places number choosen.
available_places = [] # register all availables places
unavailable_places = [] # register all unavailables places
parked_car_list = [] # register all parked cars at the moment
relation_car_parking_place = {} # store car and place number in which it's parked
parked_car_number = 0 # count all parked cars

As we said, let's say our parking has 12 seats in total, but you can change it in your script. Let's code now our functions! At first, we must initialize the parking spaces.

def reset_place(concerned_list, place_number):
    """ Reset all place in initial list """
    for place in range(1, place_number+1):
        concerned_list.append(place)

Then, we also need to make a place be available and unavailable if necessary. To do this, we'll define two functions.

def make_a_place_available(place_number):
    """ Add a place in available list """

    unavailable_places.remove(place_number)
    available_places.append(place_number)
    available_places.sort()
    unavailable_places.sort()
    print(f'Place n°{place_number} is now available.')

def make_a_place_unavailable(place_number):
    """Remove a place in available list"""

    unavailable_places.append(place_number)
    available_places.remove(place_number)
    available_places.sort()
    unavailable_places.sort()
    print(f'Place n°{place_number} is now unavailable.')

It can be useful (for example) to know how many places are still available. So let's define a function that does it.

def know_available_places():
    """ Display available places """

    if len(available_places) > 1:
        print(f'Available places are: {available_places}.')
    elif len(available_places) == 1:
        print(f'Only place n°{available_places} is available.')
    else:
        print('All places are unavailable.')

Alright. We can now make that a place will be available or not and know how many places are available. However, it's not enough? Indeed, we have not yet created a process in which a ticket is given to the driver to indicate the number of place where he can park his car. To define the process, think of something. According to you, how do drivers park their cars in a car park:

  • option 1: they park their vehicles by occupying the places in order (square 1, square 2, square 3, etc.)
  • option 2: they park their vehicles by occupying the places they want ( as long as it's available)

You'll be agree with me if i say that option 2 is what we see in real world. So function we are about to code will generate randomly a available parking place number and return this number.

def choose_available_place():
    """ Choose an available place and return it if it's available """

    choice = randint(1, total_parking_place)
    while choice in unavailable_places:
        choice = randint(1, total_parking_place)

    return choice

Great work! One last thing before launch the scenario. What we need to register a car and admit it on our parking ? 🤔 For example, we can distinct a car by:

  • the mark
  • the model
  • the color

I grant you, it's not enough, but we want to be simple as we can. For instance, if we need to note for each car the license plate, it can ask user more time, and made program less useful. So, let's use theses three criteria.

What we'll do now is to create a function which take car criteria and admit it to parking.

def add_a_car(car_mark, car_model, car_color):
    """Register a car with it's caracteristics in parked car list"""

    the_car = [car_color, car_mark, car_model]
    choosen_number = choose_available_place()
    parked_car_list.append(the_car)

    # link parked car to place where driver parked
    relation_car_parking_place[choosen_number] = the_car

    print(f'{car_color} {car_mark} {car_model} added to parking at place n°{choosen_number}')
    make_a_place_unavailable(choosen_number)

Now, it's time to begin scenario...

Scenario !

cinema.jpg

1rst thing to do is to fill out available_places list.

reset_place(available_places, total_parking_place)

Then, let's write rest of program.

In our program, our supermarket called Sin houn bou noumun. This in my native language (Attié) and it means The strength is with you (like in Star Wars 💪)!!!

print('******************************')
print('Welcome to "Sin hounbou noumun" market.\n')

continue_game = True # initialize a boolean which indicate if application continue or stop
while continue_game:
    # program interact with parking guard and display choices

    correct_choice = False
    user_choice = ''
    while not correct_choice:
        user_choice = input('What do you want to do?\n\
Choose wright number:\n\
    1- give a ticket to a driver (add a car)\n\
    2- make a place available (remove a car)\n\
    3- print availables places list\n\
    ')
        # Let's be sure that user choose a integer, and his choice is in [1:3]
        try:
            user_choice = int(user_choice)
            correct_choice = True

            if user_choice < 1 or user_choice > 3:
                correct_choice = False
                print('Make sure that you choose a number between 1 and 3')
            else:
                correct_choice = True

        except ValueError:
            print('Sorry, you must choose a number')
            correct_choice = False

    if user_choice == 1: # option 1: add a car

        # Ask car carasteristics to user
        car_ma = input('Enter the car mark: ')
        car_mo = input('Enter the car model: ')
        car_c = input('Enter the car color: ')

        # Avoid that user inputs not contain car caracteristics
        while len(car_ma) <= 0 or len(car_mo) <= 0 or len(car_c) <= 0:

            print('\nMake sure to fill in all the fields.')
            car_ma = input('Enter the car mark: ')
            car_mo = input('Enter the car model: ')
            car_c = input('Enter the car color: ')

        # If all is good admit car to parking and count it
        add_a_car(car_ma, car_mo, car_c)
        parked_car_number += 1
        correct_choice = False

    elif user_choice == 2: # option 2: remove a car
        print('List of parked cars:')
        # Display parked cars list
        for place, car in relation_car_parking_place.items():
            print(f'place n°{place}: {car}')

        '''here, we can add a try...except statement to 
        be sure that user enter correct answer
        '''
        place_wanted = int(input('Choose place you want to remove: '))

        place_of_removed_car = 0
        if place_wanted in unavailable_places:
            for place, car in relation_car_parking_place.items():
                if place == place_wanted:
                    parked_car_list.remove(car)
                    place_of_removed_car = place
                    esthetic_phrase = ' '.join(car) # Transform list in string
                    print(f'{esthetic_phrase} go out.')
            del(relation_car_parking_place[place_of_removed_car])
            make_a_place_available(place_wanted)

        else: # tell user that place number he choose is already available
            print(f'Sorry, {place_wanted} is already available.')

    else: # option 3: display available places
        know_available_places()

    # Ask if parking guard want exit the program
    exit_question = input('Do you want exit program? (Y/n)')

    if exit_question.lower() == 'y':
        continue_game = False

print('Bye bye! See you next time!')

if parked_car_number == 0:
    print(f'You didn\'t parked a car.')
elif parked_car_number == 1:
    print(f'You\'ve parked only {parked_car_number} car.')
else:
    print(f'You\'ve parked {parked_car_number} cars')

hourra.jpeg

That's all! You can run script! Our parking places handling application is ready! Here is a screencast about results when i executed script.

This app complete script is on github

Note that you can optimize this script by add additional features such as:

  • user authentication (for instance, you can use your knowledge about dict, tuple, list)
  • Book seats for VIPs. Suppose some customers are very regular in the supermarket. It would be nice to dedicate to them specific places of sorts that they are always available when these customers are present.

Well, here are some examples of features that can be made. Don't hesitate to improve this script by adding your personal touch. I hope you enjoyed this moment of scripting with me! For my part, it's always a pleasure to see you again on this script project: "Scripting Day"! Go, I wish you a great week and appointment in two weeks for a new script!😎

No Comments Yet