jeudi 23 février 2017

Python 2.7, hierarchy of priority (if statements in for loops)

I am currently taking a Python Databases course offered by Coursera. The link to the course may be found here: http://ift.tt/1LWehsp

I am not asking for anyone to do my homework, just for clarification on how Python 2 reads for loops and prioritizes if statements. You can download the appropriate code and XML file I'm parsing here: http://ift.tt/1k3XzKo

Everything that the program is meant to do is outside the scope of this question. Inside of the tracks.py program I come across a helper function used for extracting a value of a key inside a dictionary declared in the Library.xml file. It looks like this:

def lookup(d, key):
    found = False
    for child in d:
        if found : return child.text
        if child.tag == 'key' and child.text == key : found = True
    return None

At first glance, it didn't make sense to me how the function was checking the found boolean and returning the value for the given key prior to checking if it was there in the first place. When I try switching the two statements though, the program doesn't properly read in the data. Why is this?

If anyone wants me to post how I test and discover why this doesn't work please just let me know and I will add some outputs.

Aucun commentaire:

Enregistrer un commentaire