
- Python Basics
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Assignment Operators
- Python - Augmented Addition Operator (+=)
- Python - Comparison Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python Control Statements
- Python - Control Flow
- Python - Decision Making
- Python - If else
- Python - Match-Case Statement
- Python - The for Loop
- Python - The for-else Loop
- Python - While Loops
- Python - The break Statement
- Python - The continue Statement
- Python - The pass Statement
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Object & Classes
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Questions and Answers
- Python - Programming Examples
- Python - Quick Guide
- Python - Useful Resources
- Python - Discussion
Python - Variable Scope
A variable in Python is a symbols name to the object in computer's memory. Python works on the concept of namespaces to define the context for various identifiers such as functions, variables etc. A namespace is a collection of symbolic names defined in the current context.
Python provides the following types of namespaces −
Built-in namespace contains built-in functions and built-in exceptions. They are loaded in the memory as soon as Python interpreter is loaded and remain till the interpreter is running.
Global namespace contains any names defined in the main program. These names remain in memory till the program is running.
Local namespace contains names defined inside a function. They are available till the function is running.
These namespaces are nested one inside the other. Following diagram shows relationship between namespaces.

The life of a certain variable is restricted to the namespace in which it is defined. As a result, it is not possible to access a variable present in the inner namespace from any outer namespace.
globals() Function
Python's standard library includes a built-in function globals(). It returns a dictionary of symbols currently available in global namespace.
Run the globals() function directly from the Python prompt.
>>> globals() {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
It can be seen that the builtins module which contains definitions of all built-in functions and built-in exceptions is loaded.
Save the following code that contains few variables and a function with few more variables inside it.
name = 'TutorialsPoint' marks = 50 result = True def myfunction(): a = 10 b = 20 return a+b print (globals())
Calling globals() from inside this script returns following dictionary object −
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000263E7255250>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\user\\examples\\main.py', '__cached__': None, 'name': 'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction': <function myfunction at 0x00000263E72004A0>}
The global namespace now contains variables in the program and their values and the function object in it (and not the variables in the function).
locals() Function
Python's standard library includes a built-in function locals(). It returns a dictionary of symbols currently available in namespace of the function.
Modify the above script to print dictionary of global and local namespaces from within the function.
name = 'TutorialsPoint' marks = 50 result = True def myfunction(): a = 10 b = 20 c = a+b print ("globals():", globals()) print ("locals():", locals()) return c myfunction()
The output shows that locals() returns a dictionary of variables and their values currently available in the function.
globals(): {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000169AE265250>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\mlath\\examples\\main.py', '__cached__': None, 'name': 'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction': <function myfunction at 0x00000169AE2104A0>} locals(): {'a': 10, 'b': 20, 'c': 30}
Since both globals() and locals functions return dictionary, you can access value of a variable from respective namespace with dictionary get() method or index operator.
print (globals()['name']) #displays TutorialsPoint print (locals().get('a')) #displays 10
Namespace Conflict
If a variable of same name is present in global as well as local scope, Python interpreter gives priority to the one in local namespace.
marks = 50 # this is a global variable def myfunction(): marks = 70 # this is a local variable print (marks) myfunction() print (marks) # prints global value
It will produce the following output −
70 50
If you try to manipulate value of a global variable from inside a function, Python raises UnboundLocalError.
marks = 50 # this is a global variable def myfunction(): marks = marks + 20 print (marks) myfunction() print (marks) # prints global value
It will produce the following output −
marks = marks + 20 ^^^^^ UnboundLocalError: cannot access local variable 'marks' where it is not associated with a value
To modify a global variable, you can either update it with a dictionary syntax, or use the global keyword to refer it before modifying.
var1 = 50 # this is a global variable var2 = 60 # this is a global variable def myfunction(): "Change values of global variables" globals()['var1'] = globals()['var1']+10 global var2 var2 = var2 + 20 myfunction() print ("var1:",var1, "var2:",var2) #shows global variables with changed values
It will produce the following output −
var1: 60 var2: 80
Lastly, if you try to access a local variable in global scope, Python raises NameError as the variable in local scope can't be accessed outside it.
var1 = 50 # this is a global variable var2 = 60 # this is a global variable def myfunction(x, y): total = x+y print ("Total is a local variable: ", total) myfunction(var1, var2) print (total) # This gives NameError
It will produce the following output −
Total is a local variable: 110 Traceback (most recent call last): File "C:\Users\user\examples\main.py", line 9, in <module> print (total) # This gives NameError ^^^^^ NameError: name 'total' is not defined