How to fix local variable 'id' referenced before assignment
Question:
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
Answers:
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
No need to specify a constructor if you don’t do anything in it.
getInfo()
stops iterating when it finds the id
No need to keep on looping once it has been found.
class Info:
def getInfo(self,name):
with open("data.json") as file:
file_data = json.load(file)
for i in file_data["data"]:
if i["name"] == name:
return i["id"]
return None
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
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
No need to specify a constructor if you don’t do anything in it.
getInfo()
stops iterating when it finds the id
No need to keep on looping once it has been found.
class Info:
def getInfo(self,name):
with open("data.json") as file:
file_data = json.load(file)
for i in file_data["data"]:
if i["name"] == name:
return i["id"]
return None