Python Scope

python-scopes-ipcisco

In python programming, there is a term named as python scope. Python variable scope shows the area that any variable is usable or defined. In other words, a scope of a variable means that the location that we can use this variable.

 

There are two different python scopes. These are given below:

  • Local Scope
  • Global Sccope

 

 


You can also check Python For Loop and Python While Loop


 

Python Local Scope

 

Python Local Scope is the area that contains inside of a function. In other words, if we define a variable inside a python function, this variable is used only locally in this function. So, this is local scope.

 

Below, you can find two variables that has local scope. These are x and y.

 

def newfunc():
  x = 5
  y = 10
  print(x+y)

newfunc()

python-local-scope-ipcisco

 


You can check also Python Operators


 

Python Global Scope

 

Python Global Scope is the area that contains all the python code. Any variable creatd in the main python code is available in global scope and it can be used globally, within functions or any other places in the python code.

 

Below, you can see the variable z as a global variable that has global scope. X has local scope, so the program will give error that it can not find x.

 

z = 50
def myfunc():
  x = 300

myfunc()
print(x+z)

python-global-scope-ipcisco

We can create a global variable within a function also. To do this, we use “global” keyword before the name of the variable. If we create a variable with global keyword within a function, we can use this variable also out of this function.

 

z = 50
def myfunc():
  global x
  x = 300

myfunc()
print(x+z)

 

Here, the output will give the result of this calculation. Because, both of these variables are global variables.

 

350

 


 

Using Same Name For a Variable

 

We can use same variable name both as global and as local at the same time. This is not a problem for python programming. In the function that we define this variable, it will have a local scope, so in function the value of this local variable will be used. In the global part of the code, the global value of this variable will be used.

 

Below, there is a nice example to understand this better.

 

x = 100
def myfunc():
  x = 500
  print(x)

myfunc()
print(x)

 

The output of this code will give firstly the function result and it will print x value as 500. Then it will print the global value of x. This is 100.

 

500
100

python-scopes-ipcisco

In this lesson, we have talked about, scopes of python, Local scope and Global scope. These terms are very critical during coding. Because, variable definitions are one of the most used activities in python and the availability of these variables are important for a true code.

 

Back to: Python Programming Course > Python Basics

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand
Latest Blog Posts