Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix local variable 'id' referenced before assignment

I want to get a variable from a JSON file to python but it says that the local variable ‘id’ is referenced before assignment

def getInfo(name):
    with open("data.json") as file:
        file_data = json.load(file)

    for i in file_data["data"]:
        if i["name"] == name:
            id = i["id"]

    return id

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

id is actully defined only in the for loop scope, so define it at the getInto scope so you could return it

class Info:

    def __init__(self):
        pass
    def getInfo(self,name):
        with open("data.json") as file:
            file_data = json.load(file)
        id=None # <<< here
        for i in file_data["data"]:
            if i["name"] == name:
                id = i["id"]


        return id

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading