Python Project: Train Booking System

Photo by Xie lipton on Unsplash

Python Project: Train Booking System

·

10 min read


Project Description

The Train Booking System is a user-friendly Python program for booking and canceling train tickets. It includes features such as displaying train timetables and fares, booking tickets with dynamically generated numbers, canceling booked tickets, and terminating the program. The system operates based on a predefined timetable and allows users to choose their destination, passenger type, and receive a summary with a randomly generated booking number. It employs a dedicated list for efficient booking management, offers clear menu options, error handling, and interactive prompts, ensuring a seamless experience for users.


This is the finished code. Brief documentation of each part of the code is written below.

import sys
import random

# Intialize a variable for the passenger ticket
booking_data = []
booking_list = []

# Create dictionary in the global scope
# timetable must be a global variable
timetable = {
        'Malmö': {'Departure': '08:00', 'Arrival': '10:00'},
        'Uppsala': {'Departure': '08:00', 'Arrival': '09:30'},
        'Helsingborg': {'Departure': '09:00', 'Arrival': '11:00'},
        'Linköping': {'Departure': '10:00', 'Arrival': '11:30'},
        'Göteborg': {'Departure': '11:00', 'Arrival': '13:00'},
        'Karlstad': {'Departure': '19:00', 'Arrival': '21:00'},
        'Lund': {'Departure': '20:00', 'Arrival': '22:00'},
        'Jönköping': {'Departure': '20:00', 'Arrival': '22:00'},     
    }

fares = {
    'adult': 400,
    'child': 200,
    'pension': 300,
    'student': 300
}


# Create the display menu for the train trips
 # use timetable as a parameter
def display_timetable(timetable):      

    # prints the header
    print("\nTrain Timetable:")

    # print a dictionary, line by line, using for loop & dict.items()
    for city, times in timetable.items():
        # iterate over the keys and values in the dictionary
        departure = times['Departure']
        arrival = times['Arrival']

        # print timeline dictionary line by line
        print(f'{city}: Departure - {departure}, Arrival - {arrival}')

# Create the display menu for the train fares
 # use fares as a parameter
def display_fares(fares):
    print("Train Fares")

    for passenger, price in fares.items():
        print(f'{passenger}: {price} SEK')

# Function to book train ticket
# Use both timetable and fares dictionary
def book():
    while True:
        print('''
Book Train Ticket Menu selected. First, please choose your destination city.''')
        for city in timetable:
            print(city)

        # Prompt user input for destination
        while True:
            destination_input = input("Please choose from the destinations. Please type your destination:  ")

            try:
                destination_input = (destination_input)

                if destination_input in timetable:
                    destination_key = f'[{destination_input}]'
                    select_destination = timetable.get(destination_key)
                    print(f'Destination City: {destination_key}') 
                    break 

            except ValueError:
                print("Invalid Input. Please type your destination.")

        # Now, outside the inner loop, prompt user for passenger type
        passenger_input = input("Enter passenger type: 'adult, child, pension, student': ")

        # Check if the passenger type is in the fares dictionary
        if passenger_input.lower() in fares:
            # Retrieve the price from the fares dictionary
            price = fares[passenger_input.lower()]

        # Generate a random booking number
        booking_number = random.randint(1000, 9999)

        # Add booking information to the booking_data list
        booking_data.append({
                'BookingNumber': booking_number,
                'Destination City': destination_input,
                'PassengerType': passenger_input,
                'Price': price
            })

        # Add booking number to the booking_list
        booking_list.append(booking_number)

        # Print a summary of the ticket order
        print(f'\nTicket booked successfully!\nPlease give your booking number to the counter to pay and verify your ticket.\nBooking Number: {booking_number}')
        print(f'Destination: {destination_input}')
        print(f'Passenger Type: {passenger_input}')
        print(f'Price: {price} SEK')
        break  # Exit the loop after successful booking


# Function to cancel train booking
def cancel():
    print("\nTrain Booking Cancellation Menu")

    try:
        booking_number_input = int(input(" Type your booking number here: \n"))


        # check first if booking number is valid
        if booking_number_input in booking_list:
            # Retrieve the booking data using the booking number
            booking = next(item for item in booking_data if item["BookingNumber"] == booking_number_input)
            print("Booking Information:")
            print(f'Booking Number: {booking["BookingNumber"]}')
            print(f'Destination: {booking["Destination City"]}')
            print(f'Passenger Type: {booking["PassengerType"]}')
            print(f'Price: {booking["Price"]} SEK') 

                # Confirm cancellation
            confirmation = input("Do you really want to cancel this booking? (yes/no): ").lower()

            if confirmation == 'yes':
                print(f'Booking {booking_number_input} cancelled.\n')
                booking_data.remove(booking)
                return

            elif confirmation == 'no':
                print("Cancellation aborted.\n")
                return

            else:
                print("Type (yes/no)\n")


        print("Invalid booking number. Please try again.")

    except ValueError:
        print("Invalid booking number. Please try again")


# Function to exit the program
def exit_program():
    print("Program terminates")
    sys.exit()

while True:
    # Display menu and get user input
    option = input("\nMenu:\n [1] Display train timetable and passenger fares \n [2] Book a Ticket\n [3] Cancel Train Booking \n [4] Terminate Program \n Enter number here:  ")

    try:
        # converts input into integers, catches non-numeric input.
        option = int(option)

        if option == 1:
            display_timetable(timetable)
            print("\n")
            display_fares(fares)

            # Ask prompt if user wants to return to main menu
            return_menu = input("***Press any key to return to main menu. Press 'n' to exit***:  ").lower()
            if return_menu != 'n':
                print("Go back to main menu")
                continue
            elif return_menu == 'n':
                print("Booking stops. Goodbye!")
                break

        elif option == 2:
            book()

            # Ask prompt if user wants to return to main menu
            return_menu = input("***Press any key to return to main menu. Press 'n' to exit***:  ").lower()
            if return_menu != 'n':
                print("Go back to main menu")
                continue
            elif return_menu == 'n':
                print("Booking stops. Goodbye!")
                break

        elif option == 3:
            cancel()
        elif option == 4:
            exit_program()
        else:
            print("Invalid option. Please choose 1, 2, 3, or 4")

    except ValueError:
        # Tells user to try again if ValueError is caught
        print("Wrong input. Please choose 1, 2, 3, or 4")

Variables

  • booking_data: A list to store information about booked tickets, including booking number, destination city, passenger type, and price.

  • booking_list: A list specifically designed to store randomly generated booking numbers for efficient management and cancellation.

  • timetable: A global dictionary containing the timetable of train routes, with departure and arrival times for various cities.

  • fares: A dictionary defining the fare prices for different passenger types (adult, child, pension, student).

  • Functions

display_timetable(timetable)

  • Displays the train timetable with departure and arrival times for each city.

display_fares(fares)

  • Displays the train fares for different passenger types.

book()

  • Guides users through the process of booking a train ticket.

  • Users select a destination city and specify their passenger type.

  • Generates a random booking number for the ticket and stores booking information in booking_data and the booking number in booking_list.

cancel()

  • Allows users to cancel a booked ticket by providing the booking number.

  • Checks if the booking number exists in booking_list and retrieves corresponding booking data from booking_data.

  • Confirms the cancellation with the user and removes the booking data from both booking_list and booking_data if confirmed.

exit_program()

  • Terminates the program when called.

Display Timetable and Fares Dictionary

Description
This function is responsible for displaying the train timetable, including departure and arrival times for various cities. It iterates through the provided timetable dictionary and prints the information in a formatted manner.

Parameters:

  • timetable (dict): A dictionary containing the train timetable with cities as keys and departure/arrival times as nested dictionaries.

Functionality:

  1. Header Printing: Prints a header indicating that the following information is the train timetable.

  2. Iteration through timetable: Utilizes a for loop to iterate over the keys (cities) and values (departure/arrival times) in the timetable dictionary.

  3. Printing Information: Prints the timetable information for each city, displaying the departure and arrival times.

display_fares(fares)
Description: This function is responsible for displaying the train fares for different passenger types. It iterates through the provided fares dictionary and prints the information in a formatted manner.

Parameters:

  • fares (dict): A dictionary containing the train fares with passenger types as keys and corresponding prices.

Functionality:

  1. Header Printing: Prints a header indicating that the following information is the train fares.

  2. Iteration through fares: Utilizes a for loop to iterate over the keys (passenger types) and values (fare prices) in the fares dictionary.

  3. Printing Information: Prints the fare information for each passenger type, displaying the price in SEK (Swedish Krona).


Documentation of Functions

book() function

Description
This function guides users through the process of booking a train ticket within the Train Booking System. It prompts users to choose their destination city and specify their passenger type, generating a random booking number for the ticket. The booking information, including the destination, passenger type, and price, is then stored in the booking_data list, and the booking number is added to the booking_list.

Functionality:

  1. City Selection:

    • Displays a menu for users to choose their destination city.

    • Prompts the user to input their chosen destination city.

    • Validates the input to ensure it corresponds to a city in the predefined timetable dictionary.

  2. Passenger Type Input:

    • Prompts the user to input their passenger type (adult, child, pension, or student).

    • Validates the input to ensure it is a valid passenger type in the predefined fares dictionary.

  3. Generate Booking Number:

    • Generates a random booking number between 1000 and 9999.
  4. Store Booking Information:

    • Creates a dictionary containing the booking information, including the booking number, destination city, passenger type, and price.

    • Appends this dictionary to the booking_data list.

  5. Store Booking Number:

    • Appends the generated booking number to the booking_list for efficient management.
  6. Print Booking Summary:

    • Prints a summary of the booked ticket, including the booking number, destination, passenger type, and price in SEK.
  7. Exit Loop:

    • Exits the loop after a successful booking.

cancel() function

Description
The cancel() function allows users to cancel a booked train ticket. It prompts users to input their booking number and verifies its validity by checking if it exists in the booking_list. If the booking number is valid, it retrieves the corresponding booking information from booking_data. Users are then asked to confirm the cancellation, and if confirmed, the booking is removed from the system.

Functionality:

  1. Cancellation Menu:

    • Displays a menu for canceling train bookings.
  2. Input Booking Number:

    • Prompts the user to input their booking number.
  3. Validate Booking Number:

    • Checks if the inputted booking number is in the booking_list, ensuring its validity.
  4. Retrieve Booking Information:

    • Retrieves the booking information from booking_data based on the booking number.
  5. Print Booking Information:

    • Prints the booking information, including the booking number, destination city, passenger type, and price in SEK.
  6. Confirm Cancellation:

    • Asks the user to confirm the cancellation by typing 'yes' or 'no'.
  7. Cancellation Execution:

    • If confirmed, removes the booking from booking_data.

    • If canceled, prints a cancellation message.

    • If input is not 'yes' or 'no', prompts the user to type 'yes' or 'no' again.

  8. Error Handling:

    • Handles potential errors, such as invalid input or a non-existing booking number.

exit_program() function

Description
The exit_program() function terminates the Train Booking System program when called. It prints a termination message and then uses the sys.exit() function to exit the Python script.

Functionality:

  1. Termination Message:

    • Prints a message indicating that the program is terminating.

Exit Program:

  • Utilizes sys.exit() to terminate the Python script immediately.


While loop

Main Menu Loop Description
The main loop of the Train Booking System presents a menu to the user and processes their input based on their chosen option. It continuously loops until the user decides to terminate the program.
  1. Option 1: Display train timetable and passenger fares

    • Calls the display_timetable() function to show the train timetable.

    • Calls the display_fares() function to show passenger fares.

    • Asks the user if they want to return to the main menu or exit the program.

  2. Option 2: Book a Ticket

    • Calls the book() function to initiate the process of booking a train ticket.

    • Asks the user if they want to return to the main menu or exit the program.

  3. Option 3: Cancel Train Booking

    • Calls the cancel() function to initiate the process of canceling a booked train ticket.
  4. Option 4: Terminate Program

    • Calls the exit_program() function to terminate the program.
  5. Invalid Option Handling:

    • If the user enters an option other than 1, 2, 3, or 4, prints a message indicating that the input is invalid.

    • If the user enters a non-numeric value, prints a message indicating the wrong input and prompts them to choose a valid option.

      Disclosure:

    • This article was written with the assistance of ChatGPT, a powerful language model developed by OpenAI. While I initiated the project idea, coded, and provided insights, ChatGPT played a role in generating certain parts of the content. The collaboration aims to combine human creativity with AI capabilities for informative and engaging content.