0

I was trying to understand a recursive function and in order to do that I felt like I needed to create a smaller example for myself. My own code, however, is throwing me a NoneType error. I don't really have a purpose with my function, I just want to know why the error occurs?

def recursive(seq):
    if not seq:
        return [seq]
    else:
        seq2=seq[1:]
            print('seq2= ',seq2)
            print('Type seq2 = ',type(seq2))
        for i in recursive(seq2):
            print('hi')

Input:

recursive('123')

Output:

seq2=  23
Type seq2 =  <class 'str'>
seq2=  3
Type seq2 =  <class 'str'>
seq2=  
Type seq2 =  <class 'str'>
hi
Traceback (most recent call last):
    File "<pyshell#12>", line 1, in <module>
        recursive('123')
    File "C:/Python34/myreqursive(del).py", line 8, in recursive
        for i in recursive(seq2):
    File "C:/Python34/myreqursive(del).py", line 8, in recursive
        for i in recursive(seq2):
TypeError: 'NoneType' object is not iterable

1 Answer 1

3

Your else branch doesn't return anything, so the default return value None is given instead.

Rather than just print, at least return the recursive result:

def recursive(seq):
    if not seq:
        return [seq]
    else:
        seq2=seq[1:]
        print('seq2= ',seq2)
        print('Type seq2 = ',type(seq2))
        recursive_result = recursive(seq2)
        for i in recursive_result:
            print('hi')
        return recursive_result
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, sorry for that. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.