A Beginner's Guide to a Simple Car Rental System Using CRUD Principles.
Web applications are powerful, but many essential programs run directly in the command line (CMD) or terminal. These applications are fast, lightweight, and great for learning core programming logic.
In this tutorial, we will build a complete car rental management system that runs in your terminal. We will implement the four fundamental **CRUD** operations: **C**reate (add a car), **R**ead (view cars), **U**pdate (change a car's status), and **D**elete (remove a car).
To create a menu-driven CMD program where a user can manage a list of rental cars. All you need is Python installedβno extra libraries are required.
To keep things simple, we won't use a database. Instead, we'll store our car data in memory using a Python **list**. Each item in the list will be a **dictionary**, where each dictionary represents one car. This structure is intuitive and easy to manage.
# This is how our data will be structured.
cars = [
{'id': 1, 'make': 'Toyota', 'model': 'Camry', 'year': 2022, 'status': 'Available'},
{'id': 2, 'make': 'Honda', 'model': 'Accord', 'year': 2023, 'status': 'Rented'},
# ... more cars can be added here
]
Every good CMD application needs a main loop that keeps the program running and a menu to show the user their options. Let's create this skeleton first.
# We'll start with some sample data.
cars = [
{'id': 1, 'make': 'Toyota', 'model': 'Camry', 'year': 2022, 'status': 'Available'},
{'id': 2, 'make': 'Honda', 'model': 'Civic', 'year': 2023, 'status': 'Rented'}
]
next_id = 3 # To keep track of the next available ID for new cars
def display_menu():
print("\n--- Car Rental System Menu ---")
print("1. View All Cars")
print("2. Add a New Car")
print("3. Update Car Status")
print("4. Delete a Car")
print("5. Exit")
# Main application loop
while True:
display_menu()
choice = input("Enter your choice (1-5): ")
if choice == '1':
# Call function to view cars (we'll build this next)
print("Viewing cars...")
elif choice == '2':
# Call function to add a car
print("Adding a car...")
elif choice == '3':
# Call function to update a car
print("Updating a car...")
elif choice == '4':
# Call function to delete a car
print("Deleting a car...")
elif choice == '5':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")
This is the simplest operation. We'll create a function that iterates through our `cars` list and prints the details of each car in a nicely formatted table.
def view_cars(car_list):
print("\n--- List of All Cars ---")
if not car_list:
print("There are no cars in the system.")
return
# Print table headers
print(f"{'ID':<5}{'Make':<15}{'Model':<15}{'Year':<10}{'Status':<15}")
print("-"*60)
for car in car_list:
print(f"{car['id']:<5}{car['make']:<15}{car['model']:<15}{car['year']:<10}{car['status']:<15}")
Now, we can replace the placeholder `print("Viewing cars...")` in our main loop with a call to this function: `view_cars(cars)`.
This function will ask the user for the new car's details, create a new dictionary, and append it to our list.
def add_car(car_list):
global next_id # Use the global variable for the ID
print("\n--- Add a New Car ---")
make = input("Enter car make: ")
model = input("Enter car model: ")
while True:
try:
year = int(input("Enter car year: "))
break
except ValueError:
print("Invalid year. Please enter a number.")
new_car = {
'id': next_id,
'make': make,
'model': model,
'year': year,
'status': 'Available' # New cars are available by default
}
car_list.append(new_car)
next_id += 1 # Increment the ID for the next car
print(f"Success! Car '{make} {model}' added with ID {new_car['id']}.")
We'll replace the placeholder in the main loop with `add_car(cars)`.
Updating allows us to change existing data. In our system, the most common update will be changing a car's status from "Available" to "Rented," or vice-versa.
def update_car_status(car_list):
print("\n--- Update Car Status ---")
view_cars(car_list) # Show cars so user can pick an ID
if not car_list:
return
try:
car_id = int(input("Enter the ID of the car to update: "))
except ValueError:
print("Invalid ID. Please enter a number.")
return
car_to_update = None
for car in car_list:
if car['id'] == car_id:
car_to_update = car
break
if car_to_update:
print(f"Current status of car ID {car_id}: {car_to_update['status']}")
new_status = input("Enter new status (e.g., Rented, Available): ")
car_to_update['status'] = new_status
print("Status updated successfully!")
else:
print("Error: Car with that ID not found.")
Replace the update placeholder in the main loop with `update_car_status(cars)`.
This function will remove a car's dictionary from our list entirely.
def delete_car(car_list):
print("\n--- Delete a Car ---")
view_cars(car_list) # Show cars so user can pick an ID
if not car_list:
return
try:
car_id = int(input("Enter the ID of the car to delete: "))
except ValueError:
print("Invalid ID. Please enter a number.")
return
car_to_delete = None
for car in car_list:
if car['id'] == car_id:
car_to_delete = car
break
if car_to_delete:
car_list.remove(car_to_delete)
print(f"Success! Car with ID {car_id} has been deleted.")
else:
print("Error: Car with that ID not found.")
Finally, replace the delete placeholder in the main loop with `delete_car(cars)`.
Here is the full Python script with all the functions integrated. You can copy this code, save it as a `.py` file (e.g., `rental.py`), and run it from your terminal using `python rental.py`.
# --- Data Storage ---
cars = [
{'id': 1, 'make': 'Toyota', 'model': 'Camry', 'year': 2022, 'status': 'Available'},
{'id': 2, 'make': 'Honda', 'model': 'Civic', 'year': 2023, 'status': 'Rented'}
]
next_id = 3
# --- CRUD Functions ---
def view_cars(car_list):
print("\n--- List of All Cars ---")
if not car_list:
print("There are no cars in the system.")
return
print(f"{'ID':<5}{'Make':<15}{'Model':<15}{'Year':<10}{'Status':<15}")
print("-"*60)
for car in car_list:
print(f"{car['id']:<5}{car['make']:<15}{car['model']:<15}{car['year']:<10}{car['status']:<15}")
def add_car(car_list):
global next_id
print("\n--- Add a New Car ---")
make = input("Enter car make: ")
model = input("Enter car model: ")
while True:
try:
year = int(input("Enter car year: "))
break
except ValueError:
print("Invalid year. Please enter a number.")
new_car = {'id': next_id, 'make': make, 'model': model, 'year': year, 'status': 'Available'}
car_list.append(new_car)
next_id += 1
print(f"Success! Car '{make} {model}' added with ID {new_car['id']}.")
def update_car_status(car_list):
print("\n--- Update Car Status ---")
view_cars(car_list)
if not car_list: return
try:
car_id = int(input("Enter the ID of the car to update: "))
except ValueError: