Search code examples
pythonpython-3.xpython-2.7divide-by-zero

Avoiding division by zero


I know this is basic so any help appreciated.

This is my code - i just cannot get the if statement to avoid the division by zero to work.

Can anyone help?

# problem: calculate what percent of car park spaces are occupied
# input: integers 1 or 0, 1 signals an occupied space and 0 is empty

car_park_spaces = []
          
# sub problem: number of occupied spaces
occupied = 0

for car_park_space in car_park_spaces:
    if car_park_space == 1:
        occupied += 1
    occupied_spaces = occupied

    # sub problem: find the length of the list
    percentage = occupied_spaces / len(car_park_spaces) * 100

    # output: percent of occupied spaces
    if not car_park_spaces:
        print('The list is empty')
    else:
        print ('The percentage of occupied spaces is', percentage, '%')

Solution

  • I moved the code into function so it's more structured. The function looks like this:

    def occupied_percent(car_park_spaces):
        if not car_park_spaces:
            return None
            
        occupied = 0
        total_spaces = len(car_park_spaces)
    
        for space in car_park_spaces:
            if space:
                occupied += 1
    
        return occupied / total_spaces * 100
    

    The output is a float if the percentage was computed successfully, otherwise the output is None. When using the function you have to check the return value before printing the result.

    Next I created printing function that simplifies usage:

    def print_percentage(car_park_spaces):
        result = occupied_percent(car_park_spaces)
        print('The list is empty.' if result is None else f'The percentage of occupied spaces is {result}%.')
    

    And I run some test cases:

    print_percentage([])
    print_percentage([0])
    print_percentage([1])
    print_percentage([1, 0])
    print_percentage([1, 0, 1, 1])
    

    Those produce this output:

    The list is empty.
    The percentage of occupied spaces is 0.0%.
    The percentage of occupied spaces is 100.0%.
    The percentage of occupied spaces is 50.0%.
    The percentage of occupied spaces is 75.0%.
    

    Note that the code can be probably simplified further because Python tends to use a lot of one-liners.