Why this code doesn't work? I have a global variable which I need to assign value to it by getting data from json:
regional = ''
def getData(manager):
with open("temp/" manager ".json", 'r') as j:
json_object = json.loads(j.read())
for result in json_object['results']:
username = (result['username'])
if level == 1:
regional = username
print(username)
the print at the end works and shows the username but it doesn't assign it to regional which is the global variable. It's empty. In the VSCODE, it's showing as not accessible.
CodePudding user response:
You have to declare the variable as global
to be able to modify it:
regional = ''
def getData(manager):
global regional # <- HERE
with open("temp/" manager ".json", 'r') as j:
json_object = json.loads(j.read())
for result in json_object['results']:
username = (result['username'])
if level == 1:
regional = username
print(username)
CodePudding user response:
Please use global keyword. I recommand you to reference this page : https://www.geeksforgeeks.org/global-keyword-in-python/