Skip to content Skip to sidebar Skip to footer

Python Function Exit Does Not Work - Why?

Why doesn't exit() stop the script after the first iteration? In my opinion, it has to stop after the first iteration. >>> def func(q): ... def funct(y): ... t

Solution 1:

To answer your question as directly as possible,

Why doesn't exit() stop the script after the first iteration?

Because a bare except will catch BaseException and Exception, and since exit() raises a SystemExit, which is a BaseException subclass, your code will swallow the exception and pass on each iteration.

Note the difference if you catch Exception only, which does not suppress a BaseException:

>>> from sys import exit
>>> 
>>> def func(q):
...     def funct(y):
...         try:
...             print(y)
...             exit()
...         except Exception:
...             pass
...     funct(q)
... 
>>> a = ['1','2','3','4','5','6','7']
>>> for x in a: func(x)
... 
1 # exits

Solution 2:

try: sys.exit(0) and move it to the scope of the global function

import sys 
def func(q):
    def funct(y):
        try:
            print(y)
        except:
             pass
    funct(q)
    sys.exit(0)

a=['1','2','3','4','5','6','7']
for x in a:
     func(x)

Output: 1

Post a Comment for "Python Function Exit Does Not Work - Why?"