'Loop in function doesn't have access to global variable

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.



Solution 1:[1]

Please use global keyword. I recommand you to reference this page : https://www.geeksforgeeks.org/global-keyword-in-python/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 linuxias