Python Tutorial
File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python - global variables, global variables.
Variables that are created outside of a function (as in all of the examples above) are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Create a variable outside of a function, and use it inside the function
If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.
Create a variable inside a function, with the same name as the global variable
Advertisement

The global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
If you use the global keyword, the variable belongs to the global scope:
Also, use the global keyword if you want to change a global variable inside a function.
To change the value of a global variable inside a function, refer to the variable by using the global keyword:

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Python function global variables? [duplicate]
I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (I am trying to call the global copy of a variable created in a separate function.)
Does the x that the second function uses have the same value of the global copy of x that func_a uses and modifies? When calling the functions after definition, does order matter?
- global-variables
- 1 be careful also not to assume just because you have a variable assigned in your function that python will treat references before the assignment as such. Until the first assignment, if you used x, it would not be the global one, or the local one. You will get the infamous UnboundLocalError exception in your face :) – osirisgothra Aug 22, 2015 at 1:42
- Python does not copy on assignment. – Karl Knechtel Sep 10, 2022 at 7:46
6 Answers 6
If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.
This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.
The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.
- 2 In the code that I gave, is func_B doing things (1) to the global copy of x (as gotten from func_A), (2) to a local variable x with the same value of the result of func_A, or (3) to a local variable x with no value and (in the eyes of the compiler) no relation to "some value" or the x in func_A? – Akshat Shekhar May 14, 2012 at 18:00
- x in func_B is a local variable that gets its value from the return value of the call to func_A - so I guess that would make it your (2) – Levon May 14, 2012 at 18:03
- ok, let's say x was a random sequence of some kind generated by func_A (i.e. that func_A produced a different x each time it was run.) Would running the program as written make func_b modify a different x than what was originally produced when func_a was called? If so, how can I fix it? – Akshat Shekhar May 14, 2012 at 19:00
- 1 Yes, if func_A changes the global variable during each run and returns it to func_B to use, then func_B will work with a changed value each time. I am not sure about your "how to fix it". You may want to accept the most helpful answer to your current/original question and then consider opening up a different question about what looks like a follow-up question. – Levon May 14, 2012 at 19:13
- 1 Actually it depends what x is. If x is immutable, then the x in func_B will stay in it, because it is declared locally even if they have the same value. This applies to tuples, ints... If it's an instance of a list for example and you do x.append("...") , it's the global variable x that is changed, because the local one references the global one. – jadkik94 May 14, 2012 at 19:15
Within a Python scope, any assignment to a variable not already declared within that scope creates a new local variable unless that variable is declared earlier in the function as referring to a globally scoped variable with the keyword global .
Let's look at a modified version of your pseudocode to see what happens:
In fact, you could rewrite all of func_B with the variable named x_local and it would work identically.
The order matters only as far as the order in which your functions do operations that change the value of the global x. Thus in our example, order doesn't matter, since func_B calls func_A . In this example, order does matter:
Note that global is only required to modify global objects. You can still access them from within a function without declaring global . Thus, we have:
Note the difference between create_locally and access_only -- access_only is accessing the global x despite not calling global , and even though create_locally doesn't use global either, it creates a local copy since it's assigning a value.
The confusion here is why you shouldn't use global variables.
- 3 I don't think this is very confusing in-practice, you just have to understand python's scoping rules . – Casey Kuball May 14, 2012 at 18:21
You can directly access a global variable inside a function. If you want to change the value of that global variable, use "global variable_name". See the following example:
Generally speaking, this is not a good programming practice. By breaking namespace logic, code can become difficult to understand and debug.

As others have noted, you need to declare a variable global in a function when you want that function to be able to modify the global variable. If you only want to access it, then you don't need global .
To go into a bit more detail on that, what "modify" means is this: if you want to re-bind the global name so it points to a different object, the name must be declared global in the function.
Many operations that modify (mutate) an object do not re-bind the global name to point to a different object, and so they are all valid without declaring the name global in the function.
Here is one case that caught me out, using a global as a default value of a parameter.
I had expected param to have a value of 42. Surprise. Python 2.7 evaluated the value of globVar when it first parsed the function func. Changing the value of globVar did not affect the default value assigned to param. Delaying the evaluation, as in the following, worked as I needed it to.
Or, if you want to be safe,
- That reminded me of the problem of assigning an empty list as default value . And, as in the example, use is to check if something is None , instead of the normal comparison == . – berna1111 Mar 4, 2020 at 12:48
You must use the global declaration when you wish to alter the value assigned to a global variable.
You do not need it to read from a global variable. Note that calling a method on an object (even if it alters the data within that object) does not alter the value of the variable holding that object (absent reflective magic).
- 2 This wording is unfortunate. In Python, the value assigned to a variable is a reference, so it is technically correct (and I have no doubt you meant that), but many a reader may interpret "alter the value" as "mutate the object", which is not the case -- xs.append(xs.pop(0)) works just fine without global xs . – user395760 May 14, 2012 at 17:51
- @delnan My answer is carefully worded, but I will clarify. – Marcin May 14, 2012 at 18:01
Not the answer you're looking for? Browse other questions tagged python global-variables or ask your own question .
- The Overflow Blog
- Building an API is half the battle: Q&A with Marco Palladino from Kong
- Developers think AI assistants will be everywhere, but aren’t sure how to...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- Temporary policy: ChatGPT is banned
Hot Network Questions
- List all feature classes but exclude those which start with a certain character
- What if a student doesn't understand a question because of differences in dialect?
- Notating Sheet Music with Strict Tempo for Accompaniment but Rubato for Vocalist
- Short fantasy about disappearing items - Asimov's early 1980s
- Walsh-Hadamard transform in randomness testing
- Can we explain why using `Nothing` twice on a list does not operate twice?
- Is it possible to have a resistor network whose total value is unsolvable?
- What's the name of this binding type where the pages of a book are bound at different locations?
- How were rackmount workstations wired-up to mice, keyboards, monitors, etc?
- Applying geometry nodes doesn't work on a curve object
- Why is the ongoing auction for Silicon Valley Bank started privately held (vs. publicly)?
- This is a fun little word puzzle based on a fun little number puzzle
- Extracting list elements following a specific marker
- If electric field inside a conductor is always zero, then why do free electrons move?
- How can I make the rules of my Faerie Portal free from contradiction?
- Is it possible to have seasonality at 24, 12, 8 periods in hourly based wind power data?
- Why is crystal frequency often multiplied inside a microcontroller?
- Is there a RAW or optional rule for how a player could discover what type of skill check needs to be made?
- GE historic stock price on DOD changed
- Is there a "Standard Algorithm" language, as used in academic papers?
- How to define a maths operator with two arguments?
- Implementation of a shared pointer constructors and destructor
- Would these solar systems be stable?
- Is the cabin pressure "worse" at the back of the cabin than in front?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
Python Programming
Python Global Variables
Updated on: October 21, 2022 | Leave a Comment
In this tutorial, you’ll learn what is a global variable in Python and how to use them effectively.
Goals of this lesson :
- Understand what is a global variable in Python with examples
- Use global variables across multiple functions
- Learn how to use the global keyword to modify the global variables
- Learn to use global variables across Python modules/files
- Understand the use of globals() function
- Use global variables inside a nested function
Table of contents
What is a global variable in python, global variable and local variable with same name, modify a global variable inside a function, create a global variable inside a function, rules of global keyword, global variables across python modules/files, globals() function in python, global variables in nested function.
In Python, a variable declared outside the function or in global scope is known as a global variable. We can use global variables both inside and outside the function.
The scope of a global variable is broad. It is accessible in all functions of the same module .

Let’s understand it with an example.
In this example, we declared a global variable name with the value ‘Jessa’. The same global variable name is accessible to everyone, both inside of functions and outside.
Using Global Variables In Function
We can use global variables across multiple functions of the same module.
Now, let’s see how to use the global variable inside a Python function.
- First, create a global variable x and initialize it to 20. The same global variable x is accessible to everyone, both inside of functions and outside.
- Now, create a function with a combination of local variables and global variables.
- Create a local variable y And initialize it to 30. A local variable is declared inside the function and is not accessible from outside it. The local variable’s scope is limited to that function only where it is declared.
- In the end, add a global variable x and local variable y to calculate the sum of two variables.
Note : If you create a new local variable inside a function with the same name as a global variable, it will not override the value of a global variable. Instead, the new variable will be local and can only be used inside the function. The global variable with the same name will remain unchanged.
global Keyword in Python
The global keyword is used in the following two cases.
- To access and modify a global variable inside a function
- To create a new global variable inside a function
let’s see the below code.
Execute the above code to change the global variable x’s value. You’ll get an UnboundLocalError because Python treats x as a local variable, and x is also not defined inside my_func(). i.e, You cannot change or reassign value to a global variable inside a function just like this.
Use the global keyword to change the value of a global variable inside a function .
in Python, the scope of variables created inside a function is limited to that function. We cannot access the local variables from outside of the function. Because the scope is local, those variables are not visible outside the function.
To overcome this limitation, we can use the global keyword to create a global variable inside a function. This global variable is accessible within and outside the function.
Let us see the rules we need to follow to create and use a global keyword.
- If we create a variable inside a function, it is a local variable by default.
- If we create a variable outside the function, it turns into a global variable, and we don’t have to use the keyword global.
- We use the keyword global to create a global variable inside a function or to change a global variable already declared outside the function.
- Using the global keyword outside the function does not make any difference.
By default, the global variables are accessible across multiple functions of the same module . Now, we’ll see how to share global variables across the modules.
- First, create a special module config.py and create global variables in it.
- Now, import the config module in all application modules, then the module becomes available for a global name.
Let us understand it using an example.
In Python, to create a module, write Python code in the file, and save that file with the .py extension.
Example : Share global variables across Python modules.
config.py : The config module stores global variables of school and grade
Now, run the config.py file.
company.py : create a company.py file to import global variables and modify them. In the company.py file, we import the config.py module and modify the values of the name and address.
Now, run the company.py file.
employee.py :
Now, in the employee file, we import both config and company modules to test the values of global variables and whether they are changed.
As you can see in the output, we successfully accessed and modified the global variables across the files or modules.
In this section, we’ll see what the globals() do in Python.
We can also use the globals() function to access and modify the global variables . The globals() function returns the dictionary of the current global symbol table.
The global symbol table stores all information related to the program’s global scope and is accessed using the globals() method.
Function and variables are not part of any class, or functions are stored in a global symbol table.
Example : Modify the global variable using the globals() function.
Now, Let’s see how to use a global variable in a nested function. Global variables can be used in a nested function using global or nonlocal keywords.
The difference between nonlocal and global is that global is used to change global variables, while nonlocal is used to change variables outside the function. Let us illustrate this with an example.
Example : Access global variables in nested functions using the global keyword
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
Related Tutorial Topics:
Python exercises and quizzes.
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ
Leave a Reply Cancel reply
your email address will NOT be published. all comments are moderated according to our comment policy.
Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>
About PYnative
PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .
Explore Python
- Learn Python
- Python Basics
- Python Databases
- Python Exercises
- Python Quizzes
- Online Python Code Editor
- Python Tricks
To get New Python Tutorials, Exercises, and Quizzes
Legal Stuff
We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .
Copyright © 2018–2023 pynative.com
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
Mastering Data Analytics
- DevOps Engineering - Planning to Production
CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Python Programming Language
- Introduction To PYTHON
- Python Language advantages and applications
- Download and Install Python 3 Latest Version
- Python 3 basics
- Python Keywords
- Namespaces and Scope in Python
- Statement, Indentation and Comment in Python
- How to assign values to variables in Python and other languages
- Taking input in Python
- Taking input from console in Python
- Taking multiple inputs from user in Python
- Python | Output using print() function
- How to print without newline in Python?
- Python end parameter in print()
- Python | sep parameter in print()
- Python | Output Formatting
- Python Operators
- Ternary Operator in Python
- Division Operators in Python
- Operator Overloading in Python
- Any All in Python
- Operator Functions in Python | Set 1
- Operator Functions in Python | Set 2
- Difference between == and is operator in Python
- Python Membership and Identity Operators
- Python | Set 3 (Strings, Lists, Tuples, Iterations)
- Python String
- Python Lists
- Python Tuples
- Python Sets
- Python Dictionary
- Python Arrays
- Python If Else
- Chaining comparison operators in Python
- Python For Loops
- Python While Loop
- Python break statement
- Python Continue Statement
- Python pass Statement
- Looping Techniques in Python
- Python Functions
- *args and **kwargs in Python
- When to use yield instead of return in Python?
- Generators in Python
- Python lambda
Global and Local Variables in Python
- Global keyword in Python
- First Class functions in Python
- Python Closures
- Decorators in Python
- Decorators with parameters in Python
- Memoization using decorators in Python
- Python Classes and Objects
- Constructors in Python
- Destructors in Python
- Inheritance in Python
- Types of inheritance Python
- Encapsulation in Python
- Polymorphism in Python
- Class or Static Variables in Python
- Class method vs Static method in Python
- Python Exception Handling
- Python Try Except
- Errors and Exceptions in Python
- Built-in Exceptions in Python
- User-defined Exceptions in Python with Examples
- NZEC error in Python
- File Handling in Python
- Open a File in Python
- How to read from a file in Python
- Writing to file in Python
- Python append to a file
- Regular Expression in Python with Examples | Set 1
- Regular Expressions in Python – Set 2 (Search, Match and Find All)
- Python Regex: re.search() VS re.findall()
- Verbose in Python Regex
- Password validation in Python
- Python Collections Module
- Counters in Python | Set 1 (Initialization and Updation)
- OrderedDict in Python
- Defaultdict in Python
- ChainMap in Python
- Namedtuple in Python
- Deque in Python
- Collections.UserDict in Python
- Collections.UserList in Python
- Collections.UserString in Python
- OS Module in Python with Examples
- Functional Programming in Python
- Metaprogramming with Metaclasses in Python
- Abstract Classes in Python
- Multithreading in Python | Set 1
- Multithreading in Python | Set 2 (Synchronization)
- Multiprocessing in Python | Set 1 (Introduction)
- Multiprocessing in Python | Set 2 (Communication between processes)
- Socket Programming in Python
- Socket Programming with Multi-threading in Python
- NumPy Tutorial
- Python Numpy
- Numpy | ndarray
- Numpy | Array Creation
- Numpy | Indexing
- Basic Slicing and Advanced Indexing in NumPy Python
- Numpy | Data Type Objects
- Numpy | Iterating Over Array
- Numpy | Binary Operations
- Numpy | Mathematical Function
- Numpy | String Operations
- Numpy | Linear Algebra
- Numpy | Sorting, Searching and Counting
- Random sampling in numpy | randint() function
- Random sampling in numpy | random_sample() function
- Random sampling in numpy | ranf() function
- Random sampling in numpy | random_integers() function
- Numpy ufunc | Universal functions
- Pandas Tutorial
- Introduction to Pandas in Python
- How to Install Python Pandas on Windows and Linux?
- Python | Pandas DataFrame
- Creating a Pandas DataFrame
- Python | Pandas Series
- Creating a Pandas Series
- Python | Pandas Dataframe/Series.head() method
- Python | Pandas Dataframe.describe() method
- Dealing with Rows and Columns in Pandas DataFrame
- Python | Pandas Extracting rows using .loc[]
- Python | Extracting rows using Pandas .iloc[]
- Indexing and Selecting Data with Pandas
- Boolean Indexing in Pandas
- Pandas GroupBy
- Python | Pandas Merging, Joining, and Concatenating
- Python | Working with date and time using Pandas
- Python | Pandas Working With Text Data
- Python | Read csv using pandas.read_csv()
- Python | Working with Pandas and XlsxWriter | Set – 1
- Django Tutorial
- Django Basics
- Django Introduction and Installation
- Django Project MVT Structure
- How to Create a Basic Project using MVT in Django ?
- How to Create an App in Django ?
- Django Forms
- Render HTML Forms (GET & POST) in Django
- Django form field custom widgets
- Django ModelForm – Create form from Models
- Django Formsets
- Django ModelFormSets
- Django Templates
- Views In Django | Python
- Django CRUD (Create, Retrieve, Update, Delete) Function Based Views
- Class Based Generic Views Django (Create, Retrieve, Update, Delete)
- Django Models
- Django ORM – Inserting, Updating & Deleting Data
- Django Basic App Model – Makemigrations and Migrate
- Python JSON
- Working With JSON Data in Python
- Read, Write and Parse JSON using Python
- Append to JSON file using Python
- Serializing JSON data in Python
- Deserialize JSON to Object in Python
- Working with csv files in Python
- Reading CSV files in Python
- Writing CSV files in Python
- Python MySQL
- Connect MySQL database using MySQL-Connector Python
- Python MySQL – Create Database
- Python: MySQL Create Table
- Python MySQL – Insert into Table
- Python MySQL – Select Query
- Python MySQL – Where Clause
- Python MySQL – Order By Clause
- Python MySQL – Delete Query
- Python MySQL – Drop Table
- Python MySQL – Update Query
- Python MySQL – Limit Clause
- Python MySQL – Join
- Python MongoDB Tutorial
- Installing MongoDB on Windows with Python
- MongoDB and Python
- Create a database in MongoDB using Python
- Python MongoDB – insert_one Query
- Python MongoDB – insert_many Query
- Python MongoDB – Find
- Python MongoDB – Query
- Python MongoDB – Sort
- MongoDB python | Delete Data and Drop Collection
- Python Mongodb – Delete_one()
- Python Mongodb – Delete_many()
- Python MongoDB – Update_one()
- Python MongoDB – Update_many Query
- Python MongoDB – Limit Query
- Python MongoDB – create_index Query
- Python MongoDB – drop_index Query
- OpenCV Python Tutorial
- Introduction to OpenCV
- How to Install OpenCV for Python on Windows?
- Reading an image in OpenCV using Python
- OpenCV | Saving an Image
- Arithmetic Operations on Images using OpenCV | Set-1 (Addition and Subtraction)
- Arithmetic Operations on Images using OpenCV | Set-2 (Bitwise Operations on Binary Images)
- Image Resizing using OpenCV | Python
- Image Processing in Python (Scaling, Rotating, Shifting and Edge Detection)
- Python | Image blurring using OpenCV
- Erosion and Dilation of images using OpenCV in python
- Python | Thresholding techniques using OpenCV | Set-1 (Simple Thresholding)
- Python | Thresholding techniques using OpenCV | Set-2 (Adaptive Thresholding)
- Python | Thresholding techniques using OpenCV | Set-3 (Otsu Thresholding)
- Filter Color with OpenCV
- Python | Bilateral Filtering
- Python | Background subtraction using OpenCV
- Python | Play a video using OpenCV
- Extract images from video in Python
- Face Detection using Python and OpenCV with webcam
- Selenium Python Tutorial
- Selenium Basics – Components, Features, Uses and Limitations
- Components of Selenium
- Selenium Python Introduction and Installation
- Navigating links using get method – Selenium Python
- Interacting with Webpage – Selenium Python
- Locating single elements in Selenium Python
- Locating multiple elements in Selenium Python
- Locator Strategies – Selenium Python
- Action Chains in Selenium Python
- Exceptions – Selenium Python
- Python Tkinter Tutorial
- Introduction to Tkinter
- What are Widgets in Tkinter?
- Python | Creating a button in tkinter
- Python Tkinter – Label
- RadioButton in Tkinter | Python
- Python Tkinter – Checkbutton Widget
- Python Tkinter – Canvas Widget
- Combobox Widget in tkinter | Python
- Python Tkinter – Entry Widget
- Python Tkinter – Text Widget
- Python Tkinter – Message
- Python | Menu widget in Tkinter
- Python Tkinter – SpinBox
- Progressbar widget in Tkinter | Python
- Python-Tkinter Scrollbar
- Python Tkinter – ScrolledText Widget
- Python Tkinter – ListBox Widget
- Python Tkinter – Frame Widget
- Python Tkinter – Scale Widget
- Hierarchical treeview in Python GUI application
- Python-Tkinter Treeview scrollbar
- Python Tkinter – Toplevel Widget
- Python | askopenfile() function in Tkinter
- Python | asksaveasfile() function in Tkinter
- Python – Tkinter askquestion Dialog
- Python Tkinter – MessageBox Widget
- Python | place() method in Tkinter
- Python | grid() method in Tkinter
- Python | pack() method in Tkinter
- Python | PanedWindow Widget in Tkinter
- Python | Binding function in Tkinter
- Python Tkinter – Validating Entry Widget
- Kivy Tutorial
- Introduction to Kivy ; A Cross-platform Python Framework
- Python | Add Label to a kivy window
- Python | Textinput widget in kivy
- Python | Canvas in kivy
- Python | Checkbox widget in Kivy
- Python | Dropdown list in kivy
- Python | Carousel Widget In Kivy
- Python | BoxLayout widget in Kivy
- Python | Slider widget in Kivy
- Python | Popup widget in Kivy
- Python | Switch widget in Kivy
- Python | Spinner widget in kivy
- Python | Progress Bar widget in kivy
- Python | Working with buttons in Kivy
- Python | Float Layout in Kivy
- GridLayouts in Kivy | Python
- Python | StackLayout in Kivy
- Python| AnchorLayout in Kivy
- Python | Relative Layout in Kivy
- Python | PageLayout in Kivy
- Matplotlib Tutorial
- Python Seaborn Tutorial
- Python Plotly tutorial
- Python Bokeh tutorial – Interactive Data Visualization with Bokeh
- Tableau Tutorial
- Python Programming Examples
- Python Exercises, Practice Questions and Solutions
- Python Multiple Choice Questions
- Difficulty Level : Easy
- Last Updated : 14 Mar, 2023
- Discuss(20+)
Python Global variables are those which are not defined inside any function and have a global scope whereas Python local variables are those which are defined inside a function and their scope is limited to that function only. In other words, we can say that local variables are accessible only inside the function in which it was initialized whereas the global variables are accessible throughout the program and inside every function.
Python Local Variables
Local variables in Python are those which are initialized inside a function and belong only to that particular function. It cannot be accessed anywhere outside the function. Let’s see how to create a local variable.
Creating local variables in Python
Defining and accessing local variables
Can a local variable be used outside a function?
If we will try to use this local variable outside the function then let’s see what will happen.
Python Global Variables
These are those which are defined outside any function and which are accessible throughout the program, i.e., inside and outside of every function. Let’s see how to create a Python global variable.

Create a global variable in Python
Defining and accessing Python global variables.
The variable s is defined as the global variable and is used both inside the function as well as outside the function.
Note: As there are no locals, the value from the globals will be used but make sure both the local and the global variables should have same name.
Why do we use Local and Global variables in Python?
Now, what if there is a Python variable with the same name initialized inside a function as well as globally? Now the question arises, will the local variable will have some effect on the global variable or vice versa, and what will happen if we change the value of a variable inside of the function f()? Will it affect the globals as well? We test it in the following piece of code:
If a variable with the same name is defined inside the scope of the function as well then it will print the value given inside the function only and not the global value.
Now, what if we try to change the value of a global variable inside the function? Let’s see it using the below example.
To make the above program work, we need to use the “global” keyword in Python. Let’s see what this global keyword is.
The global Keyword
We only need to use the global keyword in a function if we want to do assignments or change the global variable. global is not needed for printing and accessing. Python “assumes” that we want a local variable due to the assignment to s inside of f(), so the first statement throws the error message. Any variable which is changed or created inside of a function is local if it hasn’t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword “global” , as can be seen in the following example:
Example 1: Using Python global keyword
Now there is no ambiguity.
Example 2: Using Python global and local variables
Please Login to comment...
- vaibhavsinghtanwar
- nikhilaggarwal3
- surinderdawra388
- kushagra_01
- sheetal18june
- surajkr_gupta
Data Structures & Algorithms in Python - Self Paced
Python programming foundation -self paced, master java programming - complete beginner to advanced, complete machine learning & data science program, competitive programming - live, javascript foundation - self paced, data structures and algorithms - self paced, python backend development with django - live, master c programming with data structures, master c++ programming - complete beginner to advanced, complete test series for service-based companies, complete interview preparation - self paced, java backend development - live, improve your coding skills with practice, start your coding journey now.
Learn Python interactively.
Learn Python practically and Get Certified .
Popular Tutorials
Popular examples, reference materials.
Learn Python Interactively
Python Introduction
- Getting Started
- Keywords and Identifier
- Python Comments
- Python Variables
- Python Data Types
- Python Type Conversion
- Python I/O and Import
- Python Operators
- Python Namespace
Python Flow Control
- Python if...else
- Python for Loop
- Python while Loop
- Python break and continue
- Python Pass
Python Functions
- Python Function
- Function Argument
- Python Recursion
- Anonymous Function
- Global, Local and Nonlocal
Python Global Keyword
- Python Modules
- Python Package
Python Datatypes
- Python Numbers
- Python List
- Python Tuple
- Python String
- Python Dictionary
Python Files
- Python File Operation
- Python Directory
- Python Exception
- Exception Handling
- User-defined Exception
Python Object & Class
- Classes & Objects
- Python Inheritance
- Multiple Inheritance
- Operator Overloading
Python Advanced Topics
- Python Iterator
- Python Generator
- Python Closure
- Python Decorators
- Python Property
- Python RegEx
- Python Examples
Python Date and time
- Python datetime Module
- Python datetime.strftime()
- Python datetime.strptime()
- Current date & time
- Get current time
- Timestamp to datetime
- Python time Module
- Python time.sleep()
Related Topics
Python Namespace and Scope
Python Closures
Python locals()
- List of Keywords in Python
- Python globals()
Python Variable Scope
In this tutorial, we'll learn about Python Global variables, Local variables, and Nonlocal variables with the help of examples.
Video: Python Local and Global Variables
In Python, we can declare variables in three different scopes: local scope, global, and nonlocal scope.
A variable scope specifies the region where we can access a variable. For example,
Here, the sum variable is created inside the function, so it can only be accessed within it (local scope). This type of variable is called a local variable.
Based on the scope, we can classify Python variables into three types:
- Local Variables
- Global Variables
- Nonlocal Variables
Python Local Variables
When we declare variables inside a function, these variables will have a local scope (within the function). We cannot access them outside the function.
These types of variables are called local variables. For example,
Here, the message variable is local to the greet() function, so it can only be accessed within the function.
That's why we get an error when we try to access it outside the greet() function.
To fix this issue, we can make the variable named message global.
Python Global Variables
In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.
Let's see an example of how a global variable is created in Python.
This time we can access the message variable from outside of the greet() function. This is because we have created the message variable as the global variable.
Now, message will be accessible from any scope (region) of the program.
Python Nonlocal Variables
In Python, nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.
We use the nonlocal keyword to create nonlocal variables.For example,
In the above example, there is a nested inner() function. We have used the nonlocal keywords to create a nonlocal variable.
The inner() function is defined in the scope of another function outer() .
Note : If we change the value of a nonlocal variable, the changes appear in the local variable.
Table of Contents
- Global Variables in Python
- Local Variables in Python
- Global and Local Variables Together
- Nonlocal Variables in Python
Sorry about that.
Related Tutorials
Python Tutorial
Python Library
Try PRO for FREE
- Coding Ground
- Corporate Training

- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
- Python 3 Advanced Tutorial
- Python 3 - Classes/Objects
- Python 3 - Reg Expressions
- Python 3 - CGI Programming
- Python 3 - Database Access
- Python 3 - Networking
- Python 3 - Sending Email
- Python 3 - Multithreading
- Python 3 - XML Processing
- Python 3 - GUI Programming
- Python 3 - Further Extensions
- Python 3 Useful Resources
- Python 3 - Questions and Answers
- Python 3 - Quick Guide
- Python 3 - Tools/Utilities
- Python 3 - Useful Resources
- Python 3 - Discussion
How to use a global variable in a Python function?
There are 2 types of variables in python namely Local variables and Global variables. Local variables mean the variables that are declared inside a function or inside a method whose impact or scope is only present inside that specific block and it doesn’t affect the program outside that block.
Global variables mean the variables that are declared outside any function or method and these variables have an impact or scope through the entire program.
We can also instantiate global variables inside a function by using a global keyword, if we want to declare global variables outside a function then we may not need to use a global keyword.
If a variable with the same name globally and locally then inside the function where the local variable is declared the local value is used and the global value is used elsewhere.
Let us see an example for a global variable in python −
Following is another example for this −
In the following example we are defining two global variables after the function −
Now let us let us try to create a global variable with in a function using the “ global ” keyword −
Following example shows how the global variable is accessed both inside and outside the function sample.

- Related Articles
- How to define global variable in a JavaScript function?
- How to declare a global variable in Python?
- How to use Global Variable in Postman Request?
- How to use variable-length arguments in a function in Python?
- How to create and use Global Variable in swift
- How do I declare a global variable in Python class?
- How to declare a global variable in C++
- How to declare a global variable in PHP?
- How to set a global variable in Postman?
- How to create a Global Variable in Postman?
- How to change the value of a global variable inside of a function using JavaScript?
- Create global variable in jQuery outside document.ready function?
- How to detect whether a Python variable is a function?
- How to use variable number of arguments to function in JavaScript?
- How to use a variable in a string in jQuery?

Global Variable in Python – Non-Local Python Variables
In Python and most programming languages, variables declared outside a function are known as global variables. You can access such variables inside and outside of a function, as they have global scope.
Here's an example of a global variable:
The variable x in the code above was declared outside a function: x = 10 .
Using the showX() function, we were still able to access x because it was declared in a global scope.
Let's take a look at another example that shows what happens when we declare a variable inside a function and try to access it elsewhere.
In the example above, we declared x inside a function and tried to access it in another function. This resulted in a NameError because x was not defined globally.
Variables defined inside functions are called local variables. Their value can only be used within the function where they are declared.
You can change the scope of a local variable using the global keyword – which we'll discuss in the next section.
What is the global Keyword Used for in Python?
The global keyword is mostly used for two reasons:
- To modify the value of a global variable.
- To make a local variable accessible outside the local scope.
Let's look at some examples for each scenario to help you understand better.
Example #1 - Modifying a Global Variable Using the global Keyword
In the last section where we declared a global variable, we did not try to change the value of the variable. All we did was access and print its value in a function.
Let's try and change the value of a global variable and see what happens:
As you can see above, when we tried to add 2 to the value of x , we got an error. This is because we can only access but not modify x .
To fix that, we use the global variable. Here's how:
Using the global keyword in the code above, we were able to modify x and add 2 to its initial value.
Example #2 - How to Make a Local Variable Accessible Outside the Local Scope Using the global Keyword
When we created a variable inside a function, it wasn't possible to use its value inside another function because the compiler did not recognize the variable.
Here's how we can fix that using the global keyword:
To make it possible for x to be accessible outside its local scope, we declared it using the global keyword: global x .
After that, we assigned a value to x . We then called the function we used to declare it: X()
When we called the showX() function, which prints the value of x declared in the X() function, we did not get an error because x has a global scope.
In this article, we talked about global and local variables in Python.
The examples showed how to declare both global and local variables.
We also talked about the global keyword which lets you modify the value of a global variable or make a local variable accessible outside its scope.
Happy coding!
This author's bio can be found in his articles!
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

IMAGES
VIDEO
COMMENTS
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a
If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword. E.g.
How to Use Global Keywords in Python With Examples? ; x = 5. #initializing a global variable ; def life(). #defining a function ; global x. #using global keyword.
Using Global Variables In Function · First, create a global variable x and initialize it to 20. · Now, create a function with a combination of
A global keyword is a keyword that allows a user to modify a variable outside the current scope. It is used to create global variables in Python
Global and Local Variables in Python · Global variables are those which are not defined inside any function and have a global scope whereas local
Python Global Variables ... In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global
Global variables mean the variables that are declared outside any function or method and these variables have an impact or scope through the
When you define a variable outside a function, like at the top of the file, it has a global scope and it is known as a global variable. A global
In Python and most programming languages, variables declared outside a function are known as global variables. You can access such variables