The word scope simply means boundary. However, for an operation to be carried out in python, there must be a value assigned to a defined variable. We should know by now that variables only operate within a defined boundary known as Variable Scope. However, it’s recommended that before you proceed into the scope concept you should reverse Python Variables. Good thing, we’ll brush on it also on this page because delving deep into the Python Scope.
At the end of this page, you’ll be thankful for a clear understanding on:
- Variable Initialization: Revision
- What is Variable scope(Python Scope)?
- Local Scope
- Nonlocal Scope
- Global Scope
- Built-in Scope
In summary, you’ll be refreshed to be able to put the knowledge to work.
Revision: Python Variable
A Variable is a name given to a storage location that holds the data that you want to program. It’s stored on the go.
When you hear the word variable, you understand it to be an object or character that represents a value. These values can be numbers (0-9), alphabets (Aa-Zz), or alphanumerics (R5cY). In mathematics, an equal sign(=) is used to show the value of a variable, like this b=2+4. In Python Language programming, the computer needs to store code values which afterward will be located and interpreted to effect its purpose. The container/memory that stores or represents these values for readability is called a variable. In this way, a variable represents string literals or statements in Coding.
Example of Variables:
gender = 'F' message = ''best friend ever''
In the examples above, gender and message are the variables, ‘F’ and “best friend ever” are the values of the variables
Note: there’s no command prompt for variable execution in python, it’s self executes once you initialize(=) a value to a variable
Uses Of Variables
The use of variables in python is straight to point and that is to reserve memory for values to be stored. And it’s used to represent string literals; a string is a list of characters that makes up a code line.
Types of Variables in Python
The Python Language has three variables, which are:
- int(whole numbers)
- Float(decimals)
- Complex(complex numbers)
Variable Initialization
As stated earlier, to be able to assign values to Variables in Python accurately, you must understand its arrangement. The left operand is for the variables while the right operand is for the values assigned to the variables. There’s no command to affect a variable, just introduce the equal to sign(=) and python will interpret it.
Example:
Input
#!/usr/bin/python3 counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "Simon" # A string print (counter) print (miles) print (name)
This means that counter, miles, and name are the variables while 100, 1000.0, and “Simon” are the values assigned to the variables.
Output
100 1000.0 Simon
Interestingly, you can assign a single value to multiple variables.
Example:
a = b = c = 1
Also, you can assign multiple objects to multiple variables on one line of code
Example:
a, b, c = 1, 2, “Simon”
Click here for more info on the Python Variable. The main idea I want you to grab is how you initialize(=) a variable. Now the goal is achieved, let’s move on to the main
What is a Variable Scope in python?
In Python, not all variables can be accessed from anywhere in a program, meaning that they operate within a boundary. The location in a program where a variable can be accessed is called variable scope. In Python, there are four variable scopes which are: Local, Enclosing, Global, and Built-in. They form the basis for the LEGB rule. The scope gives a set of rules on how a variable can be searched and where it should be searched. However, a code is not visible to the entire program that’s because its visibility is restricted. Scope determines which variables can be visible. To locate a variable, you use the namespace to search it out either for value derivation or value assignment.
Delving deeper into the scopes…
Local Scope
The local scope is used to mean the names that are defined within a function and are limited to that function. The local scope operates till the end of a code block in which it was defined and stays on as long as the function is still executing
Example:
Python Input
def myfunc(): x = 400 print(x) myfunc() Output: 400
The variable x falls within the function that gives us the return of 400. On the contrary, trying to define a variable outside the functions will raise an error report.
NonLocal Scope
The nonlocal scope variable stands in between global and local scope. They are used to operate nested functions whose local scope is not defined. The nonlocal keyword is used to create the nonlocal variable. The nonlocal scope known as the enclosing scope is simply the function within a function that has another function in it.
Example:
Python Input
def outer(): x = "local" def inner(): nonlocal x x = "nonlocal" print("inner:", x) inner() print("outer:", x) outer()
Output: inner: nonlocal outer: nonlocal
The returns above show a function inside the scope of another function. However, a nonlocal keyword was used to create a nonlocal variable. If the value of the nonlocal keyword is changed, the edits will surface on the local keyword
Global Scope
As the name implies, Global scope variables can be accessed from anywhere in the program; from within the function and from outside the function.
Example:
Python Input
x = "global" def foo(): print("x inside:", x) foo() print("x outside:", x)
Output: x inside: global x outside: global
In the code returns, x is a global variable. The def foo() was used to print out the global variable x. Conclusively, the foo() was called out which printed the variable value of x.
Let’s see what will happen if we want to change the value of x within the function
Python Input
x = "global" def foo(): x = x * 2 print(x) foo()
Output: Traceback (most recent call last): File https://extendsclass.com/lib/Brython-3.8.9/www/src/Lib/site-packages/editor.py, line 116, in run exec(src, ns) File <string>, line 7, in <module> File <string>, line 4, in foo UnboundLocalError: local variable 'x' referenced before assignment
The return is an error because you can not access a local variable in a global scope. And python values x to be a local variable that is not defined in the foo() function
Built-in Scope
The built-in scope is like a container that contains all the other reserved keywords when the interpreter is started. These keywords are easy to call from anywhere in the program and can be used without the need to define them.
Example
Python Input
# Built-in Scope from math import pi # pi = 'Not defined in global pi' def func_outer(): # pi = 'Not defined in outer pi' def inner(): # pi = 'not defined in inner pi' print(pi) inner() func_outer()
Output: 3.141592653589793
Summary
A Variable is a name given to a storage location that holds the data that you want to program. It’s stored on the go.
The use of variables in python is straight to point and that is to reserve memory for values to be stored. And it’s used to represent string literals; a string is a list of characters that makes up a code line.
There’s no command to affect a variable, just introduce the equal to sign(=) and python will interpret it.
In Python, not all variables can be accessed from anywhere in a program, meaning that they operate within a boundary.
The location in a program where a variable can be accessed is called variable scope. In Python, there are four variable scopes which are: Local, Enclosing, Global, and Built-in. They form the basis for the LEGB rule.
At the end of this page you learned the following:
- Variable Initialization: Revision
- What is Variable scope(Python Scope)?
- Local Scope
- Nonlocal Scope
- Global Scope
- Built-in Scope
The choice is on you to give it all it takes to be the Pythonista you’ve dreamt of. For a helping hand see the Python Tutorials. Good luck Coding!