简体   繁体   中英

Python return statement doesn't break for loop

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'

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'

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