- 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
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
Global vs Local variables in Python
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.
#!/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
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
- Global and Local Variables in Python?
- Global and Local Variables in C#
- Global and Local Variables in Java
- What are local variables and global variables in C++?
- Member variables vs Local variables in Java
- System variables vs Local Variables in MySQL?
- What is the difference between global and local variables in Python?
- What are the rules for local and global variables in Python?
- User-defined variables vs Local Variables in MySQL?
- How are C++ Local and Global variables initialized by default?
- Global variables in Java
- Global and Local Inversions in C++
- Local variables in Java
- Global Scope Variables in Postman?