I Need Help With My Python Code Car Park

I am working on my code for accessing a car park txt file by the user selecting displaying the current file, seeing the statistics of the occupancy and then reserving a slot, and then eventually quitting the program.

Right now with how I have it set up only the menu is printing and when you select one of the options the program ends. I am not quite sure what I am doing wrong here. If someone could offer a nudge in the right direction would be super! I am not sure if I can post this here or not, remove it if it is not allowed.

How do I access the car park file for display, statistics, and reserve successfully with the menu?

# The function of this program is to show the user current layout of a car park, provide statistics and reserve a spot

file_name = "carpark.txt"
car_dataset = []


# this is the user menu

print("D to display current status of car park")
print("R to reserve an empty slot in the car park")
print("S to display % occupancy of the car park")
print("Q to Quit program")

user_input = input("Please enter your selection here:")




# this will display the current car park text file

def display():
    if user_input == "D":
        f = open("carpark.txt", "r")
        with open("carpark.txt") as file_name:
            file = file_name.read()
            print(file)


# this will display the occupancy of the car park file

def statistics():
    if user_input == "S":
        count = 10
        total = 80
        for row in file_name:
            for col in row:
                if (col == 'X'):
                    count += 1
        print('Occupancy % : ', end='')
        print((count * 100) / total)


# this will allow the user to reserve a spot to car park file

def reserve():
    global row, col
    if user_input == "R":
        row = int(input('Enter the desired row for reservation: '))
        col = int(input('Enter the desired col for reservation: '))
    try:
        if file_name[row][col] == 'X':
            print('Parking slot is already occupied')
        elif (col > 6):
            print('Parking slot is not available')
        else:
            file_name[row][col] = 'X'
            print('Parking slot booked successfully!')
    except:
        if user_input == ("M", "N", "O", "S"):
            print('Invalid input')


# this will display the file, occupancy, and reserve the spot

if __name__ == "__main__":
    display()
    statistics()
    reserve()

I see a number of problems here:

  • Your functions don’t accept parameters and expect all variables to be global. They aren’t (and shouldn’t be). For example if you create a variable in display() it’ll be gone when the function returns. Use parameters and return values to pass data to/from functions.

  • The menu code needs to be after the main guard (so it will only run if your file is run as a script).

  • If you want to process multiple commands, you need to create a loop:

    • Read a command
    • Process the command
    • Repeat until done (the Q command)

Thank you for your help! I believe I am more or less on the right track, I got some extra help. I am overthinking this project a lot.

I got my menu in a while loop but had to use break to get it stop going on and on forever. Now I am just tidying up my code and trying to create a close neighbor algorithm to find the closest parking slot near the building by searching 2x2 then 4x4, then 8 x 8. I am looking over code samples from my course but alas I am still stuck and I need a little bit of help, how does one build a algorithm?


file_name = "carpark.txt"
car_dataset = []


# this is the user menu
def menu():
    while True:
        print("""
        Choose option to continue:
        D to display current status of car park
        R to reserve an empty slot in the car park
        S to display % occupancy of the car park
        Q to Quit program 
        """)
        break


# this is where the user will make their selection
def choice():
    user_input = input("Please enter your selection here:")
    return user_input


# this will display the current car park text file
def display(car_dataset):

    print('  AB CD EF GH')
    for i, row in enumerate(car_dataset):
        print(i+1, row)


# this will display the occupancy of the car park file
def statistics(car_dataset):
    count = 0
    total = 0

    for row in car_dataset:
        for col in row:
            if col == 'X':
                count += 1
            if col != ' ':
                total += 1

    print('Occupancy % : ', end='')
    print((count * 100) / total)


# this will allow the user to reserve a spot to car park file
def reserve(car_dataset):
    column_indexes = {'A': 0, 'B': 1, 'C': 3, 'D': 4, 'E': 6, 'F': 7, 'G': 9, 'H': 10}
    row = int(input('Row: '))
    col_letter = input('Col: ')
    col = column_indexes[col_letter]

    try:
        if car_dataset[row-1][col] == 'X':
            print('Parking slot is already occupied')
        if car_dataset[row - 1][col] == '.':
            #car_dataset[row-1][col] = 'X'
            print('Parking slot booked successfully!')
            #assign(car_dataset, col, row-1)
    except:
        print('Invalid input')

# this will assign the closest spot for the reservation
def assign(car_dataset, row, column):
    for i in range(len(row)):
        if row[i] == car_dataset:
            return i
        return -1
    print("")






if __name__ == "__main__":
    menu()
    user_choice = choice()

    file = open("carpark.txt", "r")
    car_dataset = [e.strip() for e in file.readlines()]
    file = file.close()

    if user_choice == 'D':
        display(car_dataset)
    if user_choice == 'S':
        statistics(car_dataset)
    if user_choice == 'R':
        reserve(car_dataset)

Using break to leave the loop is good here, but you have the loop in the wrong place. If you want the menu() function to just print the possible choices you don’t need a loop there. You need a loop where you process the choices, and then break if the user enters Q:

    while True:
        menu()
        user_choice = choice()
        if user_choice == 'Q':
            break
        elif # handle other choices here...

I recommend loading the dataset before the loop so you only have to do that once. :wink:

An “algorithm” is a structured way to solve a problem. Step away from the code for a while, look at the grid layout, and describe the process you want to use (like “look at field x, y, if it’s free…”). After that you can express that in code.