i've been doing the "Automate the Boring Stuff with Python Programming" course, and I don't understand why author says that the reason of None value being in output is a fact, that there is no return statement in function below. I I thought that "return 42/divideBy" is a return statement that is needed. I am very much new in the world of programming, so i would appreciate an easy explanation. Thanks
def div42by (divideBy):
try:
return 42/divideBy
except ZeroDivisionError:
print ('Error: You tried to divide by zero.')
print (div42by(2))
print (div42by(12))
print (div42by(0))
print (div42by(1))
(output)
21.0
3.5
Error: You tried to divide by zero.
None
42.0
You are correct that return 42/divideBy
is a return statement.
But when divideBy
is equal to zero, the 42/divideBy
part will raise a ZeroDivisionError
, which means the return
never actually runs. Instead, Python jumps to the print ('Error: You tried to divide by zero.')
line and continues running from there. There's no return
statement after that line, so Python automatically returns None
instead.
Another way to look at it is that your div42by
function is equivalent to this:
def div42by(divideBy):
try:
result = 42 / divideBy
return result
except ZeroDivisionError:
print('Error: You tried to divide by zero.')
And the return result
line never runs when divideBy
is zero.