-4

this is my code.

def percent_of_goal(donation, goal): 
    """ percentofgoal
    """
    perc = float(goal/donation)
    return  100/perc

but when I do print(percent_of_goal(0, 1000)) with 0 as the donation, I get a zero division error? how do I fix this?

error message:

*** RUN TIME ERROR(S) ***
Traceback (most recent call last):
  File "source.py", line 8, in <module>
    result = percent_of_goal(0, 1000)
  File "source.py", line 4, in percent_of_goal
    perc = goal/donation
ZeroDivisionError: division by zero
Stardom
  • 23
  • 1
  • 6

4 Answers4

1

The first line in your function is causing the problem... perc = float(goal/donation)

Reverse your ratio by replacing with this (Considering this note: You do not need to deal with the case of a goal of zero):

def percent_of_goal(donation, goal): 
    """ percentofgoal
    """
    return (donation/goal) * 100

Otherwise, just add a simple if statement:

def percent_of_goal(donation, goal): 
    """ percentofgoal
    """
    return (donation/goal) * 100 if goal != 0 else 0
Jonathan Hamel
  • 1,393
  • 13
  • 18
0

To calculate the donation-to-goal ratio, you should divide donation by the goal, rather than the other way around:

def percent_of_goal(donation, goal): 
    perc = donation / goal
    return  perc * 100
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

Before using the division operator, you should always check that your denominator is valid, and provide an alternate output that is appropriate to your use case.

In this example, perhaps you want a function like this instead of using /:

def protected_div(n, d):
    return float(n)/d if d != 0 else 0
matt2000
  • 1,064
  • 11
  • 17
-1

The problem is you can not divide by zero (just regular math) perhaps you could try using an if statement, where the perc returns zero if the donation <= 0:

if donation <= 0:
  perc = 0
else:
  perc = goal/donation
5824
  • 3
  • 3