简体   繁体   中英

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.

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.

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)

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.

The function 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

The following while loop runs as long as there is no result .

while (result := add()) is None:
    print('you made a mistake, make sure to input two numbers!')

# use result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM