A variable is an important and ubiquitous concept in programming. Variables are containers for storing data. Variables can store many types of data, including usernames, email addresses, and items from a user’s online game inventory.
When programming in Python, you come across two types of variables: global and local. In this guide, we discuss the difference between these two types of variables, how they work, and how you can use them in your code.
Python Variables
In Python, variables are primarily used to label and store data. When you define a variable, you give it a name. You can then use this name later in your code to retrieve the data it represents. Variables can store strings, numbers, lists, or any other type of data.
Suppose you are creating a game and want to store a username. Instead of having to type the name into our program, we can use a variable to store it.
Here is a variable that stores the name of a user for a game:
We have declared a variable called name and set it to "Carlton Hernandez".
Now that we have declared this variable, we can manipulate it in our code. For example, if we wanted to change our username, we could do so using this code:
In the first line of our code, we have assigned the value "Carlton Hernandez" to the variable name . Thus, we have assigned the value "Carlton Lewis Hernandez" to the variable name. When you assign a new value to a variable, the program overwrites the most recent value, replacing it with the new one.
Python Global Variables
There are two main types of variables in Python: local and global.
Global variables are variables declared outside of a function. Global variables have a global scope. This means that it is accessible throughout the program, including functions. Consider the following visual representation of this concept.
Global and local variables in Python
A global variable is accessible via a program.
Here is an example of a global variable in Python:
Once we have declared a global variable, we can use it in all of our code. For example, we can create a function that prints the value contained by our global variable name using the following code:
Our code returns:
Here we have initialized a called function printName (). This function, when invoked, prints the value of the name variable to the console. This is what happened above when we called the function.
Python local variables
Local variables, on the other hand, are variables declared inside a function. These variables are known to have local scope. This means that they are only accessible in the function in which they are declared. Consider again this visual representation we showed earlier which describes the concept of variables in Python:
Global and local variables
A local variable can only be accessed in a function particular.
Here is an example of a program that uses a local variable:
Our code returns:
In our code, we declared a fun called printName (). In this function we have defined a variable called name. Since we have declared this variable inside a function, it is a local variable.
At the end of our code, we called our function using printName (). In response, the program executed the printName () function.
The name variable in this example is local to printName (). Therefore, we cannot access this variable outside of our function. Here’s what happens when we try to print this local variable name outside of the function it’s declared in:
Our code returns:
We can’t access a local variable outside of the function we’ve assigned that variable to. When we try to access a local variable in our main program, the program throws an error.
Using global and local variables
It is possible for a program to use the same name of variable for both a local variable and a global variable. The local variable will be read in the local scope and the global variable will be read in the global scope.
Here is an example of a program that has local and global variables with the same name:
Our code returns:
First, we assigned the global variable score in our code, then in our calculateScore () , we created a local variable with the same name.
The value of our local variable score in the calculateScore () The function is equal to 10. So when it calls our function calculateScore (), the message Final score: 10 is printed on the console.
However, apart from our calculateScore (), the value of the variable score is 5. This is because we set the value of the variable score in the global scope to 5. So when we print Initial score:, followed by the value of the variable score , the program displays the value 5.
Assigning global variables within a function
In the previous sections, we learned that global variables are defined outside of a function (i.e. globally) and local variables are defined within a function (e.g. locally). However, if you use the global keyword to define a variable in a function (e.g., locally) and then run that function in the program (globally), that variable will become a global variable.
Consider the following example:
Our code returns:
In our code, we assigned the value of the variable name locally, inside setName () function. However, since we used the global keyword before defining this variable, we are preparing to give the name variable global scope. However, the name variable will become a global variable only after the execution of this function in the program.
After the program executes the setName () function, each time we use the name variable in our program, as we did when we executed the print () function, the program will use the value we declared in the local function, because the name variable is now a global variable variable.
Remember how we said earlier that it is not possible directly to modify a global variable within a function ? That’s true. However, you can use the global keyword to indirectly modify a global variable in a function.
Here is an example program that uses the global keyword in a function to change the has the value of a global variable:
Our code returns:
Let’s break this code down. We first declared a variable called name and assigned the value "Bianca Peterson" to it. It is a global variable. So we have declared a function called setName (). When called, the setName () function modifies the value of the name variable.
Next, we called setName (), which changed the value of name to "Bianca Lucinda Peterson‚". Finally, we printed the value of name to the console. The value of the name global variable is now "Bianca Lucinda Peterson‚".
In general, the global keyword should be used sparingly. Too frequent use of the global keyword can make it difficult to understand the scope of variables in a program.
Conclusion
Global variables are variables declared outside of a function. Local variables are variables declared in a function.
Although global variables cannot be changed directly in a function, you can use the global keyword to create a function that will change the value of a global variable. In this case, the value of the global variable will not change until you run this function.
This tutorial explained, referring to examples, the basics of local and global variables and how they work. . You are now ready to start using local and global variables in your Python code like a professional programmer !
We hope this article has helped you to resolve the problem. Apart from Local Variable And Global Variable In Javascript, check other __main__ Python module-related topics.
Thanks for explaining! I was stuck with Local Variable And Global Variable In Javascript for some hours, finally got it done 🤗. Will use it in my bachelor thesis
Jan Wu
Abu Dhabi | 2023-02-01
Maybe there are another answers? What Local Variable And Global Variable In Javascript exactly means?. Will use it in my bachelor thesis
Angelo Gonzalez
San Francisco | 2023-02-01
Thanks for explaining! I was stuck with Local Variable And Global Variable In Javascript for some hours, finally got it done 🤗. I am just not quite sure it is the best method
Shop
Learn programming in R: courses
$FREE
Best Python online courses for 2022
$FREE
Best laptop for Fortnite
$399+
Best laptop for Excel
$
Best laptop for Solidworks
$399+
Best laptop for Roblox
$399+
Best computer for crypto mining
$499+
Best laptop for Sims 4
$
Latest questions
PythonStackOverflow
Common xlabel/ylabel for matplotlib subplots
1947 answers
PythonStackOverflow
Check if one list is a subset of another in Python
1173 answers
PythonStackOverflow
How to specify multiple return types using type-hints
1002 answers
PythonStackOverflow
Printing words vertically in Python
909 answers
PythonStackOverflow
Python Extract words from a given string
798 answers
PythonStackOverflow
Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?