Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Variable Scope in Python

In general, a variable that is defined in a block is available in that block only. It is not accessible outside the block. Such a variable is called a local variable. Formal argument identifiers also behave as local variables.

The following example will underline this point. An attempt to print a local variable outside its scope will raise the NameError exception.

Example: Local Variable
def greet():
  name = 'Steve'
  print('Hello ', name)
  
greet()
print(name) #NameError
Try it

Here, name is a local variable for the greet() function and is not accessible outside of it.

Any variable present outside any function block is called a global variable. Its value is accessible from inside any function. In the following example, the name variable is initialized before the function definition. Hence, it is a global variable.

Example: Global Variable
name='John'
def greet():
  print ("Hello ", name)
  
greet()  
print(name)
Try it

Here, you can access the global variable name because it has been defined out of a function.

However, if we assign another value to a globally declared variable inside the function, a new local variable is created in the function's namespace. This assignment will not alter the value of the global variable. For example:

Example: Local and Global Variables
name = 'Steve'
def greet():
    name = 'Bill'
    print('Hello ', name)  #Hello Bill

greet()  
print(name) #steve
Try it

Now, changing the value of global variable name inside a function will not affect its global value.

If you need to access and change the value of the global variable from within a function, this permission is granted by the global keyword.

Example: Access Global Variables
name = 'Steve'
def greet():
    global name
    name = 'Bill'
    print('Hello ', name)

greet()  
print(name) #Bill
Try it

The above would display the following output in the Python shell.

It is also possible to use a global and local variable with the same name simultaneously. Built-in function globals() returns a dictionary object of all global variables and their respective values. Using the name of the variable as a key, its value can be accessed and modified.

Example: Global Variables
name = 'Steve'
def greet():
  globals()['name'] = 'Ram'
  name='Steve'
  print ('Hello ', name)
  
greet()  
print(name) #Ram
Try it

The result of the above code shows a conflict between the global and local variables with the same name and how it is resolved.

Visit Globals and Locals in Python for more information.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.