简体   繁体   中英

Python: How to quit a recursive function when an error arises interrupting the program

Say I have a recursive function like

def func(n, lis):
    if n == 1:
        return lis
    else:
        lis = func(n-1, lis[:-1])
        print(n,lis)
        lis.append(n)
        if len(lis) < 5:
            return lis
        else:
            return 'Error'

and if I run

print (func(6, [6,5,4,3,2,1]))

I get

2 [6]
3 [6, 2]
4 [6, 2, 3]
5 [6, 2, 3, 4]
6 Error
Traceback (most recent call last):
  File "d:/Python/test.py", line 324, in <module>
    print (func(6, [6,5,4,3,2,1]))
  File "d:/Python/test.py", line 314, in func
    lis.append(n)
AttributeError: 'str' object has no attribute 'append'

The function reads the return of func(5, [6,2,3,4,5]) , which is 'Error' , and puts it into func , arising an AttributeError . This is not what I want since it stops the program. I tried

class AtLeastFive(Exception):
    pass

def func(n, lis):
    if n == 1:
        return lis
    else:
        lis = func(n-1, lis[:-1])
        print(n,lis)
        lis.append(n)
        if len(lis) < 5:
            return lis
        else:
            raise AtLeastFive

But this still interrupts the program. I need to run the function for a series of lists, so I don't want Exception . What I want is something like

for lis in lists:
    func(n, lis)

but it stops when there is an exception. Is it possible to quit the function when bad things happen without interupting the loop?

If I understand what you are trying to do, your function func should ultimately return Error for the arguments that you are passing to it. If that is the case, then the following code should work:

def func(n, lis):
    if n == 1:
        return lis
    else:
        lis = func(n-1, lis[:-1])
        print(n,lis)
        # test to see if return value is `Error` and if so, return it:
        if lis == 'Error':
            return lis
        lis.append(n)
        if len(lis) < 5:
            return lis
        else:
            return 'Error'

print (func(6, [6,5,4,3,2,1]))

Prints:

2 [6]
3 [6, 2]
4 [6, 2, 3]
5 [6, 2, 3, 4]
6 Error
Error

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