Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 720
Dutchpirate91 Avatar asked Oct 15 '25 15:10

Dutchpirate91


2 Answers

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.

A 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.

like image 110
MooingRawr Avatar answered Oct 18 '25 09:10

MooingRawr


while loop, for two reasons

  • it's clearer to read: while not success, try again
  • recursion is not free. It leaves the previous function stack open. it could run out of memory (probably won't, in this case, but in principle, avoid it)
like image 43
blue_note Avatar answered Oct 18 '25 09:10

blue_note



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!