user4461365
user4461365

Reputation: 49

python ZeroDivisionError: float division by zero - how to treat it as an exception

I need to calculate the percentage of winning rate and I am having trouble with ZeroDivisionError: float division by zero when there is zero in the denominator. I would like treat it as an exception, print zero and move on to next array. Any assistance would be appreciated.

YearWinLose1 = '0'
YearWinLoseTotalHard2 = '0'

YearWinLoseTotalHard2 = float(YearWinLose1) + float(YearWinLose1)
YearWinLosePercent3 = float(YearWinLose1)/float(YearWinLoseTotalHard2)*100

if YearWinLoseTotalHard2 == 0:
   YearWinLosePercent3 == 0
   print YearWinLosePercent3
else: 
   print YearWinLosePercent3

Upvotes: 3

Views: 18122

Answers (1)

francisco sollima
francisco sollima

Reputation: 8338

You can use try/except:

try:
    YearWinLosePercent3 = float(YearWinLose1)/float(YearWinLoseTotalHard2)*100
except ZeroDivisionError:
    print '0' #or whatever

EDIT 1:

To correct what you had written, let me make a few comments. By this line:

if YearWinLoseTotalHard2 == 0:

The error has already happened in the previous line. If you wanted to use an if-structure as a control method, you should have added the division inside the if block:

if YearWinLoseTotalHard2 != 0:
    YearWinLosePercent3 = float(YearWinLose1)/float(YearWinLoseTotalHard2)*100
else:
    print '0'

Also, you have written

YearWinLosePercent3 == 0

If you are trying to assign a value to a variable, you should know the operator is '=', not '=='. The latter is for comparing values.

Upvotes: 6

Related Questions