31.2k views
5 votes
Two variables, num_dogs and num_cats, hold the number of dogs and cats that have registered for a pet daycare. The budget variable holds the number of dollars that have been allocated to the daycare for the year. Write code that displays the per-pet budget (dollar spent per pet), rounded to two decimal places. If a division by zero error takes place, just print out the word "unavailable".

In Python

1 Answer

5 votes

Below is a Python code snippet that accomplishes what you described:

# Assuming num_dogs, num_cats, and budget are defined before this point

try:

# Calculate per-pet budget

per_pet_budget = budget / (num_dogs + num_cats)

# Display the result rounded to two decimal places

print(f"Per-pet budget: ${per_pet_budget:.2f}")

except ZeroDivisionError:

print("Unavailable - Division by zero error.")

In this code, a try-except block is used to handle the possibility of a division by zero error. If the division is successful, it calculates the per-pet budget and prints it rounded to two decimal places. If a division by zero error occurs, it prints the message "Unavailable."

User Ricree
by
8.7k points