py4e icon indicating copy to clipboard operation
py4e copied to clipboard

Division by zero: py4e/code3/average.py, py4e/code/average.py, py4e/code3/avenum.py and py4e/code/avenum.py

Open solomon-s-b opened this issue 5 years ago • 1 comments

If we type 'done' as the first input, the program will crash with a "ZeroDivisionError".

Traceback (most recent call last):
  File "readnumbers.py", line 15, in <module>
    average = total / count
ZeroDivisionError: float division by zero

Because you already mentioned 'division by zero' earlier in chapter 3 paregrgh 3.8 "Short-circuit evaluation of logical expressions" in the book and also 'Worked Exercise 5.1' on your YouTube channel, I suggest adding the following code before the print command:

if count > 0:
    average = total / count
else:
    average = 0

print('Average:', average)

instead of:

average = total / count
print('Average:', average)

solomon-s-b avatar Aug 14 '20 11:08 solomon-s-b

The examples can't cover all the possibilities, doing that would make the examples too complicated for the point that is being shown. Many of the assignments / exercises also say check for 1 type of error, or assume user enters the data correctly. That is the best way to look at it for now, enter data that the example uses.

srcatto avatar Jan 27 '21 21:01 srcatto

Thanks.

csev avatar Jan 03 '24 04:01 csev