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

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.

Leave a Comment