- 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
What are the rules for local and global variables in Python?
Scope of Variables in Python are of two types: local and global. Scope is defined as the accessibility of a variable in a region. Let us first understand both local and global scope before moving towards the rules.
This defines the local scope of a variable i.e. it can be accessed only in the function where it is defined. No access for a variable with local scope outside the function. Let’s see an example −
# Variable with local scope can only be access inside the function def example(): i = 5 print(i) # An error is thrown if the variabke with local scope # is accessed outside the function # print(i) # Calling the example() function example()
If a variable is accessible from anywhere i.e. inside and even outside the function, it is called a Global Scope. Let’s see an example −
# Variable i = 10 # Function def example(): print(i) print(i) # The same variable accessible outside the function # Calling the example() function example() # The same variable accessible outside print(i)
10 10 10
Rules for local and global variable
Following are the rules −
Variables that are only referenced inside a function are implicitly global.
If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Variable with a local scope can be accessed only in the function where it is defined.
Variable with Global Scope can be accessed inside and outside the function.
- Related Articles
- What are local variables and global variables in C++?
- Global and Local Variables in Python?
- What are the local and global scope rules in C language?
- Global vs Local variables in Python
- What is the difference between global and local variables in Python?
- Global and Local Variables in C#
- Global and Local Variables in Java
- What are the basic scoping rules for python variables?
- How are C++ Local and Global variables initialized by default?
- What are the basic rules for defining variables in C++?
- What are class variables, instance variables and local variables in Java?
- What are the rules for a local variable in lambda expression in Java?
- What are global variables in C++?
- What are local variables in C++?