Make division by zero equal to zero
Check if the denominator is zero before dividing. This avoids the overhead of catching the exception, which may be more efficient if you expect to be dividing by zero a lot.
def weird_division(n, d):
return n / d if d else 0
How to prevent division by zero exception?
An "exception" is something that the python kernel raises to let you know it found an error and the code doesn't work. For example, try
print(12/0)
You will get a "traceback" that shows all the exceptions that were handled by python (this is why python is so great, it doesn't just crash your computer when an error happens). In this case the "exception" is called ZeroDivisionError. You can handle the error yourself in a number of different ways; for example, you could prevent python from trying to divide by zero, by checking the inputs first. Let's try:
a = int(input("Give me an integer of your choice: "))
b = int(input("Give me another integer of your choice: "))
if b == 0:
print("Sorry, can't divide by zero, this will cause an error.")
else:
print(a/b)
Avoiding division by zero
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.
python: getting around division by zero
Since the log
for x=0
is minus infinite, I'd simply check if the input value is zero and return whatever you want there:
def safe_ln(x):
if x <= 0:
return 0
return math.log(x)
EDIT: small edit: you should check for all values smaller than or equal to 0.
EDIT 2: np.log
is of course a function to calculate on a numpy array, for single values you should use math.log
. This is how the above function looks with numpy:
def safe_ln(x, minval=0.0000000001):
return np.log(x.clip(min=minval))
Get infinity when dividing by zero
If you just want a float that represents infinity, you can issue float('inf')
or float('-inf')
.
Standard Python floats and ints will give you a ZeroDivisionError
, but you can use numpy
datatypes.
>>> import numpy as np
>>> np.float64(15)/0
inf
Without numpy
, write a function:
def my_div(dividend, divisor):
try:
return dividend/divisor
except ZeroDivisionError:
if dividend == 0:
raise ValueError('0/0 is undefined')
# instead of raising an error, an alternative
# is to return float('nan') as the result of 0/0
if dividend > 0:
return float('inf')
else:
return float('-inf')
Related Topics
How to Create a for Loop That Goes Through All Diagonal Possibilities of a List
Typeerror: Missing 1 Required Positional Argument: 'Self'
Replace Empty Strings With None/Null Values in Dataframe
How to Change Border Color in Tkinter Widget
Calculating Manhattan Distance in Python in an 8-Puzzle Game
Replace a Word in a String by Indexing Without "String Replace Function" -Python
How to Remove Comma and Brackets
Get All the Diagonals in a Matrix/List of Lists in Python
High Pass Filter for Image Processing in Python by Using Scipy/Numpy
Python: How to Read and Load an Excel File from Aws S3
Finding the Value of the Min and Max Pixel
Python - How to Separate Paragraphs from Text
Pandas - Drop Last Column of Dataframe
How to Copy a File to a Remote Server in Python Using Scp or Ssh
How to Disable Pylint Unused Import Error Messages in VS Code