What are the differences between using a while loop vs recursion in try, except, finally error handling?
When I use a while loop in user input error handling:
while True:
try:
user_num = float(input("Enter a number: ")
break
except ValueError as e:
print("That is not a number. Error:", e)
finally:
print("Cycle is done.")
The code loops until there are no errors and each loop prints "Cycle is done."
When I use recursion instead of a while loop:
try:
user_num = float(input("Enter a number: ")
except ValueError as e:
print("That is not a number. Error:", e)
get_num()
finally:
print("Cycle is done.")
The code loops until there is no error as well and after a success it prints "Cycle is done." * n where n = number of cycles.
Initially I expected them both to run the same.
It seems that the while loop will hit the finally section before looping, and that the recursion method is still executing the except code so after a success, every call reaches finally in LIFO order.
I read that the recursion method will eventually raise a RecursionError: maximum recursion depth exceeded error if cycled long enough.
Are there other differences between these two methods of looping error handling?
As commenters pointed out, this question could be answered with an understanding of the call stack and iteration vs recursion. I will answer my question with relevant key highlights from my research on these topics:
Iteration within a function will not add to the call stack, but recursive calls within a function will add to the call stack. Each recursion adds a stack frame to the call stack which takes memory. It's worth mentioning that Python is not designed to optimize tail recursion so as to maintain an accurate traceback. Python raises a
RecursionErrorto prevent stack overflow when the recursion limit of 1000 is reached. Therefore, iteration, even when having the same Big O notation, is faster and more space efficient. Recursion can pass information to a child function call using parameters and it can pass information back to the parent calling function using return values. This makes performing operations on trees and graphs easier.While there is no one size fits all answer, in most cases iteration is the preferable choice, especially when the goal is to repeat the code until a certain condition becomes False, like in my example. However, recursion is useful for navigating non-linear data structures and in situations when a problem can be broken down into smaller pieces.