
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Scope of Variables in Python
All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python −
- Global variables
- Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.
Example
#!/usr/bin/python total = 0; # This is global variable. # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable. print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total
Output
When the above code is executed, it produces the following result −
Inside the function local total : 30 Outside the function global total : 0
- Related Articles
- Scope of Variables in C++
- Scope of Variables in C#
- C++ Scope of Variables
- Global Scope Variables in Postman?
- What is the scope of variables in JavaScript
- Scope and lifetime of variables in Java?\n
- What is the scope of local variables in Java?
- Variables, their types, and Scope in C++
- What are Local Scope Variables in Postman?
- Access variables from parent scope in anonymous PHP function
- What do you mean by Scope of variables inside MySQL stored procedure?
- Namespaces and Scope in Python
- How variable scope works in Python function?
- Explain python namespace and scope of a variable.
- What is the scope of data science with python?

Advertisements