'returning dictionary to break recursive loop returns NoneType [duplicate]

I have a recursive function where the input dictionary is updated

def update_dict(d: dict) -> dict:
    global counter
    print(f"COUNTER:{counter}")
    keys=['a','b']
    values=[1, 2]
    for k,v in zip(keys,values):
        d.update({k:v})
    print(d)
    counter+=1
    if counter==3:
        return d
    update_dict(d)

I want to return the updated dictionary after some termination counter, but get a NoneType:

counter = 0
my_dict = update_dict({})
print(my_dict)

Output:

COUNTER:0
{'a': 1, 'b': 2}
COUNTER:1
{'a': 1, 'b': 2}
COUNTER:2
{'a': 1, 'b': 2}
None

Expected output: {'a': 1, 'b': 2}



Solution 1:[1]

    global counter
    print(f"COUNTER:{counter}")
    keys=['a','b']
    values=[1, 2]
    for k,v in zip(keys,values):
        d.update({k:v})
    print(d)
    counter+=1
    if counter==3:
        return d
    return update_dict(d)  # <--- fix is to add the return here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yoav Glazner