Home > OS >  Problem with nonexistent return statement in ZeroDivisionError in Python
Problem with nonexistent return statement in ZeroDivisionError in Python

Time:09-06

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

CodePudding user response:

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.

CodePudding user response:

The return statement is not executed because dividing by zero raises an ZeroDivisionError. This ZeroDivisionError is then caught by the try->except block.

The order in which things happen is:

  • python3 tries to execute 42 / divideBy (which is zero)
  • 42 / divideBy raises the ZeroDivisionError
  • the ZeroDivisionError is caught by the try-except
  • the except-block is executed, making python3 print the error message
  • the function continues, but there is no Code left
  • No return statement gets executed

To still get a return, there'd need to be a return statement below try->except but still inside the function.

  • Related