5) e. Local and Global Variables





Pause here and try to guess – what would happen if you run this piece of code?

If you are expecting a number 8 to be printed out, unfortunately you are mistaken. Instead you will get this error:

1
2
Output:
UnboundLocalError: local variable 'a' referenced before assignment




This happened because when you want to modify a global variable inside an inner scope, the first variable a is defined in the scope of the whole script. Then inside my_function you attempt to create a new variable called a. By itself it is fine to give variables the same names in different scopes albeit confusing and not recommended.

But in this case a is not given any value and you already try to increment it.

When you create a variable it exists inside of scope. In this image, first variable damage exists in the scope of the script. You can read its value anywhere but you can only assign new value inside the same scope.

If you want to change a variable outside of its scope you need to use the global keyword.

1
2
Output:
8

This time you are letting Python know that you are using the variable a from a different scope and you can modify its value.


Please note that using global variables can be tricky in any programming language because it becomes very difficult to keep track of the possible changes that are made to variables from unexpected places in the code.