

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- C++ Scope of Variables
- Scope of Variables in C++
- Scope of Variables in C#
- Scope and lifetime of variables in Java?
- Global Scope Variables in Postman?
- What is the scope of variables in JavaScript
- 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
- Explain python namespace and scope of a variable.
- How variable scope works in Python function?
- Private Variables in Python
Advertisements