Python Tutorials
- Python
- How to install Python?
- PIP
- How to Run Python Program
- Python Identifiers,Statement, Indentation and Comments
- Variable
- Data type
- Decision Making
- Python Loops
- Break,Continue, Pass
- Functions
- Predefine Functions
- Lambda Functions
- Variable Scope
- List
- Tuple
- Python Sets
- Python Dictionary
- Python String
- String Formating
- Input/Output
- File Handling (Input / Output)
- Iterators
- Python Modules
- Python Date
- Python JSON
- Classes and Objects
- Constructor
- Polymorphism
- Encapsulation
- inheritance
- Class or Static Variables in Python
- class method vs static method
- Abstraction
- Exception Handling
- MySql Python
- MySql Create Database
- MySql CRUD
- Django
Scope of variables in python
The scopes of the variables depend upon the location where the variable is being declared. The variable declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
File name : index.py
Local variables
Global variables
Local Scope Variable.
the variable defined inside a function is known as local scope.
File name : index.py
def print_message():
message = "hello !! I am going to print a message." # the variable message is local to the function itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be accessible here.
Example :-
File name : index.py
def exfunc():
x = 500
print(x)
exfunc()
Output :-
500
Example :-
File name : index.py
def myfunc():
x = 500
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Output :-
500
Global Scope
The variable defined outside any function is known to have a global scope. Global variables are available from within any scope, global and local.
A variable created outside of a function is global and can be used by everyone.
File name : index.py
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed Output:
Example :-
File name : index.py
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Example :-
File name : index.py
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
Output :-
200
300
Global Keyword :-
If you use the global keyword, the variable belongs to the global scope.
File name : index.py
def myfunc():
global x
x = 300
myfunc()
print(x)
Example :-
To change the value of a global variable inside a function, refer to the variable by using the global keyword:
File name : index.py
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
Output :-
200