Python return statement doesn't break for loop

Viewed 102

I would like to iterate through an XML structure. My code does seem to work. I checked the debugger and saw that it reached the return, but the for loop continues.

Looking forward to your advice, thank you!

def get_value(root, item):
    for node in root:
        if node.tag == item:
            return node.tag
        else:
            get_value(node, item)
    return 'Item not found in XML'
2 Answers

Here the issue is, you are calling the same function is else statement. So, if it enters in else block, it might go on recursively. Try to amend your code, avoiding calling the function from within. Also, you might need to place return inside for loop, highlighted below

def get_value(root, item):
    for node in root:
        if node.tag == item:
            return node.tag
        else:
            get_value(node, item) ---> This is the problem
        return 'Item not found in XML'

You forgot a return statement right when you start recursion calls. Meaning it would go on forever until max recurison limit is reached or run out of memory.

change your code like this

def get_value(root, item):
    for node in root:
        if node.tag == item:
            return node.tag
        else:
            return get_value(node, item)
    return 'Item not found in XML'
Related