variable inside class not detecting global variable in python

some_global_variable

class TestClass():
    def run(self):
        #we can access it by defining the variable as global inside the function
        global some_global_variable 
        for i in range(10):
            some_global_variable = 1
            print(some_global_variable)

Here is what the above code is Doing:
1. We create a global variable called some_global_variable.
2. We create a class called TestClass.
3. We create a function called run.
4. We define some_global_variable as global inside the function.
5. We loop 10 times and set some_global_variable to 1.
6. We print some_global_variable.

The output of the code is:

1
1
1
1
1
1
1
1
1
1

As you can see, we were able to access the global variable inside the function.

However, there is a better way to do this.

We can use the global keyword when we create the variable.

This way, we don’t have to define the variable as global inside the function.

Here’s the code: