0
Explanation of the output
#Someone can explain me the output of this code? def s(x): try: print("Hello") print(1 / x) except ZeroDivisionError: print("Divided by zero") return s(x+1) finally: print("This code will run no matter what") print(s(0)) #output: #Hello #Divided by zero #Hello #1.0 # This code will run no matter what #This code will run no matter what #None
5 odpowiedzi
+ 5
Alright, let's see. The last line says print(s(0)), so first s() will be be called with the argument 0, and the return value will be printed. We'll come back to the return value later.
s(0) starts with printing Hello. Then print(1/0) causes ZeroDivisionError, so we jump to the except block and print Divided by zero.
Now we have a return s(x+1), so s() is called again with argument 1 (=0+1). But wait! The finally clause is ALWAYS executed before leaving a try statement, even "on the way out" (Reference:
https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions ). So the code first prints the "This code will..." part and then deals with the return.
Now for s(1), we print Hello and then also 1/x, which evaluates as 1.0. No exception is raised, and we again deal with the print statement in the finally block.
Now the function call is complete, and since there's no explicit return value any more, the final return value of s(0) is the default, which is None.
So None is printed.
+ 3
You call s with 0 as the argument
Then you enter the try statement, at first it prints out hello and then you want to print 1 / x. You gave x 0 so you do 1 / 0. This raises a ZeroDivisonError so you go to the except statement. Here you print divided by zero and you return s with x + 1 or 1. After that you go into the finally statement and you print this code will run no matter what
+ 3
David Pado no problem!!
+ 2
Okok all clear, thanks 👍💪
+ 1
Thanks