0

Can someone please explain why I am getting none as return, I am updating the dictionary and b is dependent to function call so it should update too right?. Or is it referencing to previous one?

d = dict()

def rec():
    b = d.get('A')
    print('b is ',b)
    if b:
        print('here')
        return b
    else:
        d['A'] = {'yes':1}
        rec()

print('return is ',rec())
KARAN
  • 3
  • 1
  • **What books did you read about programming in Python?** Did you at least read [the documentation of Python](https://www.python.org/doc/)? There is a chapter about [debugging](https://docs.python.org/3/library/debug.html)! – Basile Starynkevitch May 04 '21 at 05:05

2 Answers2

4
d = dict()

def rec():
    b = d.get('A')
    print('b is ',b)
    if b:
        print('here')
        return b
    else:
        d['A'] = {'yes':1}
        return rec()

print('return is ',rec())

Your else needs to return back the value as well

lyncx
  • 680
  • 4
  • 8
0

You got None because the first rec() doesn't return anything (the block in the else is executed). You can add return before recursive calling to return result:

d = dict()

def rec():
    b = d.get('A')
    print('b is ',b)
    if b:
        print('here')
        return b
    else:
        d['A'] = {'yes':1}
        return rec()

print('return is ',rec())

Output:

b is  None
b is  {'yes': 1}
here
return is  {'yes': 1}
Kien Nguyen
  • 2,616
  • 2
  • 7
  • 24