Try except recursion or while loop?
I am doing a python course where they suggested a try and except block in a while loop in order to keep asking for input until the condition is satisfied. Intuitively I feel it is shorter to just call the function again in the "except" block like this:
def exceptiontest(): try: print(int(input("number 1: "))+int(input("number 2:"))) except: print("a mistake happened") exceptiontest() exceptiontest()
When asking on the forum on the course I got the reply that it is not the same. I am a bit confused now. Anyone that can clarify for me? Thanks in advance!
Calling the function in the
except will eventually raise a
RecursionError: maximum recursion depth exceeded error if you keep entering bad inputs. Generally must humans won't be entering that many bad data to hit the error before they give up, but you are unnecessarily putting function calls on a stack.
while loop is better since it's one function call, waiting for a valid input. IT doesn't waste any more resources than it needs.
Recursion is not intrinsically better or worse than loops - each has advantages I say this because a while loop is equivalent to a tail recursive function and recursive that will be passed all the way back, or throw an exception. If you take the programming language Python, it supports recursion, but by A conditional statement decides the termination of recursion while a control variable’s value decide the termination of the iteration statement (except in the case of a while loop). Infinite
102,591 else clause, try/except statement, 168 extracting subject of an article, 457 infinite recursion, 134 using with for and while loops, 105 while True/break While there are many different types of loops, almost each type of loop has the same basic function: iterating over data to analyze or manipulate it. Recursion is another popular type of function and although it can also analyze and manipulate sequences of data similar to a loop, recursion is probably less understood in many cases, and can
Another reason to use the
while loop which has not yet been mentioned is that you could leverage the assignment expressions coming with Python 3.8.
add encapsulates getting two numbers and trying to add them.
def add(): 'try to add two numbers from user input, return None on failure' x = input('number 1: ') y = input('number 2: ') try: return float(x) + float(y) except TypeError, ValueError: return None
while loop runs as long as there is no
while (result := add()) is None: print('you made a mistake, make sure to input two numbers!') # use result
try: factorial ( -5 ) raise Assertion Error , 'Factorial failed to throw exception on negative Recursion and recursive functions are a useful technique for easily Python's iteration constructs are many and varied, involving for loops, while loops, except user_input_1 != int evaluates to except True which is meaningless and will never get triggered. The only way you don't hit a break in your while loop, is if you throw an exception that gets caught (if it's not caught, it'll escape your while loop and exit your program).
Loops are very much not recursion. In fact, they are the prime example of the opposite mechanism: iteration. The point of recursion is that one Is a while loop intrinsically a recursion? Since you can define a while loop in terms of itself. while p do c := if p then (c; while p do c)) then, yes, a while loop is a form of recursion. Recursive functions are another form of recursion (another example of recursive definition). Lists and trees are other forms of recursion.
When we think about repeating a task, we usually think about the for and while loops. These constructs allow us to perform iteration over a list, collection, etc. This is a recursive loop. If thingThatSometimesCrashes crashes too many times in a row, the function will exceed the recursion limit and still crash. You could instead do a loop with a flag. function varargout = myfunc (varargin) myflag = true; while myflag. try. thingThatSometimesCrashes; myflag = false;
But what if for and while loops got axed from python tomorrow? Aside from a majority of the world ceasing to function, we have the more pressing In general, exceptions are not ideal for your situation anyway—a simple while loop should be sufficient. Exceptions should be reserved for exceptional situations, and bad user input is not exceptional, it's expected. The loop-based version of Release would look something like this: