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:

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get your certification today!

python assign global variable in function

Get certified by completing a course today!

Subscribe

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.

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?

Wolf's user avatar

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.

Cristian Ciupitu's user avatar

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.

jdotjdot's user avatar

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.

Noisy_Botnet's user avatar

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.

kindall's user avatar

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,

SoloPilot's user avatar

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).

Marcin's user avatar

Not the answer you're looking for? Browse other questions tagged python global-variables or ask your own question .

Hot Network Questions

python assign global variable in function

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 :

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 .

Python global variables

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.

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.

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.

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.

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

python assign global variable in function

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

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

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

Mastering Data Analytics

CBSE Class 12 Computer Science

Related Articles

Global and Local Variables in Python

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...

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

Python Flow Control

Python Functions

Python Global Keyword

Python Datatypes

Python Files

Python Object & Class

Python Advanced Topics

Python Date and time

Related Topics

Python Namespace and Scope

Python Closures

Python locals()

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:

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

Sorry about that.

Related Tutorials

Python Tutorial

Python Library

Try PRO for FREE

Python Tutorial

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.

Tarun Chandra

Tutorials Point

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:

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

  1. Understand global variables scope in python

    python assign global variable in function

  2. In Python, can I create a global variable inside a function and then use it in a different

    python assign global variable in function

  3. How to Assign a Function to a Variable in Python?

    python assign global variable in function

  4. Python Variables: Declare, Concatenate, Global & Local

    python assign global variable in function

  5. Python 2.7 Use Global Variable In Function

    python assign global variable in function

  6. Global Variable in Python With Examples [Updated]

    python assign global variable in function

VIDEO

  1. python code of global variable #python shorts

  2. The derivative of a multi-variable function

  3. Python Quiz #2 Global and Local Variables in Python #python

  4. A Python script to send auto message to each telegram user using telethon

  5. Local & Global Variables In Python

  6. Variable & assignments

COMMENTS

  1. Python

    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

  2. Python function global variables? [duplicate]

    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.

  3. Global Variable in Python With Examples [Updated]

    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.

  4. Python Global Variable

    Using Global Variables In Function · First, create a global variable x and initialize it to 20. · Now, create a function with a combination of

  5. Global keyword in Python

    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

  6. Global and Local 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

  7. Python Variable Scope (With Examples)

    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

  8. How to use a global variable in a Python function

    Global variables mean the variables that are declared outside any function or method and these variables have an impact or scope through the

  9. Python Global Variables

    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

  10. Global Variable in Python

    In Python and most programming languages, variables declared outside a function are known as global variables. You can access such variables