Global VariablesIn 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. Show
Let's see an example of how a global variable is created in Python. Example 1: Create a Global Variable
Output x inside: global x outside: global In the above code, we created x as a global variable and defined a What if you want to change the value of x inside a function?
Output UnboundLocalError: local variable 'x' referenced before assignment The output shows an error because Python treats x as a local variable and x is also not defined inside To make this work, we use the Local VariablesA variable declared inside the function's body or in the local scope is known as a local variable. Example 2: Accessing local variable outside the scope
Output NameError: name 'y' is not defined The output shows an error because we are trying to access a local variable y in a global scope
whereas the local variable only works inside Let's see an example on how a local variable is created in Python. Example 3: Create a Local VariableNormally, we declare a variable inside the function to create a local variable.
Output local Let's take a look at the earlier problem where
x was a global variable and we wanted to modify x inside Global and local variablesHere, we will show how to use global variables and local variables in the same code. Example 4: Using Global and Local variables in the same code
Output global global local In the above code, we declare x as a global and y as a local variable in the After calling the Example 5: Global variable and Local variable with same name
Output local x: 10 global x: 5 In the above code, we used the same name
x for both global variable and local variable. We get a different result when we print the same variable because the variable is declared in both scopes, i.e. the local scope inside When we print the variable inside Similarly, when we print the variable outside the Nonlocal VariablesNonlocal 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. Let's see an example of how a nonlocal variable is used in Python. We use Example 6: Create a nonlocal variable
Output inner: nonlocal outer: nonlocal In the above code, there is a nested
Note : If we change the value of a nonlocal variable, the changes appear in the local variable. Python also uses variables to hold data. They also have a name and a type; however, in python, you don't have to declare the data type. Instead, you can create a python variable as follows. class_number = 4; In the above example, the variable 'class_number' has the value of 4; it is an integer data type. And unlike other programming languages, you don't need to declare a variable without initializing. What Does Variable Scope in Python Mean?Variable scope means the area in which parts of a program can access the variable. There are four variable scopes in python:
In this article, you will learn the first two types. You will learn to create python variables with local and global scope. What Is the Global Variable In Python?In the programming world, a global variable in Python means having a scope throughout the program, i.e., a global variable value is accessible throughout the program unless shadowed. A global variable in Python is often declared as the top of the program. In other words, variables that are declared outside of a function are known as global variables. You can access global variables in Python both inside and outside the function. Syntax: X = “sampleGlobalValue” Def fn1(): How to Create Global Variables in Python?To create a global variable in Python, you need to declare the variable outside the function or in a global scope. Example:Output:
How to Access the Global Variable Inside and Outside of the Function?Example:
Output:
In the example depicted above, you saw a global variable declared and accessed both inside and outside of the function. So, you are accessing the value both inside and outside of the function, which is fine, but what happens if you try to modify the global scope variable value inside a function? See the example mentioned below to understand better. Example:
Output:
As it is evident, this throws an error. When you try to modify the global variable value inside a function, it will throw UnboundLocalError, because while modifying Python treats x as a local variable, but x is also not defined inside the function (myfunc()). That’s where the Global keyword comes into the picture. You will see the usage of Global Keywords in the following sections. How to Create Variables With Local Scope in Python with Examples?A local variable's scope is a function in which you declared it. To access the variable, you have to call the corresponding function. For example, you can create a local variable as shown below.
Global KeywordGlobal keyword is used to modify the global variable outside its current scope and meaning. It is used to make changes in the global variable in a local context. The keyword ‘Global’ is also used to create or declare a global variable inside a function. Usually, when you create a variable inside a function (a local variable), it can only be used within that function. That’s where the global keyword comes in the play, which helps to create global variables inside the function and which can be accessible in a global scope. Syntax: Def func(): Global variable Example 1:Use a global keyword to create a variable in the global scope.
Output:
Example 2:Use a global keyword to change the value of the global variable inside the function.
Output:
You have seen what ‘global’ keywords are, their examples, and how to use global keywords. But Python has some basic rules to use the ‘global’ keyword. Let’s see Global in Nested functions. When you declare a global keyword variable inside the nested function and when you change the global keyword variable inside the nested function, it will reflect outside the local scope, since it is used as a global keyword. Example:Let's see an example for global in nested functions.
Output:
You can see the above output for the global in nested functions. But maybe a quick following explanation will help for better understanding. You have declared the global variable inside the inner() function, which is nested inside the main() function. Before and after calling the inner(), the variable ‘integ’ takes the value of the local variable main i.e. integ = 20. Outside of the main() function, the variable ‘integ’ takes the value of the global keyword declared inside the inner() function i.e., integ = 20 as you used the global keyword inside the inner() function local scope. If you make any changes inside the inner() function global keyword variable ‘integ’, will reflect outside of the scope, as a behavior of the global keyword. The fundamental rules of the ‘global’ keyword are as follows:
How Can You Create Variables Using Global Scope in Python With Examples?You can create a variable with global scope by initializing outside all the functions in a python program. And you can access the variable from anywhere in the python program. Creating a global variable is simple; you can do it as follows.
How to Use Global Keywords in Python With Examples?If you use a variable inside a function, python thinks you are referring to a local variable. So use the global keyword to change a global variable within a python function. The following example shows the use of global keywords in a python program.
Local VariablesThe following example shows a mistake. Example 1: Accessing Local Variable Outside the Scope
In the above program, you are trying to access 'y' defined in the function loc(). And the line print(y) will give you a Name Error: name 'y' is not defined. The following example shows how to rewrite the above program. Example 2: Create a Local Variable
Global and Local VariablesAs you can not access a local variable from outside a function, it does not matter if the global and the local variables have the same name. Below you can find an example where there are two variables. One is global, and the other is local. Both have the same name. Example1: Global Variable and Local Variable With the Same Name
In the above example, the print function in the man () function accesses the local variable x with a value of 4. And the print function outside accesses the local variable with a value of 5. Difference Between Global and Local VariablesLet us see an example of how global and local variables behave in the same code. Example:
Output:
Explanation:Here in the program above, you declared x as a global and y as a local variable in the same program. Then it tried to modify the global variable using the global keyword in the local function and printing both gx and ly. Once you called function1(), the value of gx became global global. As you tried to modify as gx*2, it printed ‘global’ two times. After this, you printed the local variable ly, which displayed the local variable value i.e., again ‘local’. Difference Between Global and Nonlocal VariablesWhen a variable is either in local or global scope, it is called a nonlocal variable. Nonlocal variables are defined in the nested function whose scope is not defined. Example:
Output:
Explanation:From the above program, it can be noticed that the nested function is innerfn(). Inside the innerfn(), you saw the use of a nonlocal keyword to create a nonlocal variable. The innerfn() is defined in the scope of outerfn(). If you make changes to the value of a nonlocal variable, they reflect in the local variable. In conclusion, understanding the scope of python variables is essential for an error-free program. You can access the global variables from anywhere in the program. However, you can only access the local variables from the function. Additionally, if you need to change a global variable from a function, you need to declare that the variable is global. You can do this using the "global" keyword. Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer ConclusionVariables are one of the most basic elements of a programming language. It is an abstraction layer for the memory cells that contain the actual value. Global, Local and Nonlocal types of variables help the programmer to access some values entirely in the program scope, or some values that are limited to within the function. In this article, you learned what a global variable is in Python, how to define global variables in Python, how to declare a global variable in Python, what is a global keyword, when to use a global keyword, the difference between global, local, and nonlocal variables along with some working examples. Join Simplilearn's Python Training Course to learn more about this topic. This course will teach you the basics of Python, conditional statements, data operations, shell scripting, and Django. This certification course, which includes 38 hours of blended learning and 8 hours of online self-paced learning, will prepare you for a fulfilling career as a professional Python programmer by providing you with practical programming experience. Have any questions for us? Leave them in the comments section of this article, and our experts will get back to you on them, as soon as possible! Can we access global variable if there is a local variable with same name?Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolution operator respectively.
What happens when both local and global variables have the same name in Python?If a global and a local variable with the same name are in scope, which means accessible, at the same time, your code can access only the local variable.
How do you access global variable if there is a local variable with same name in Java?Using Scope resolution operator (::):
In C++, we can use the scope resolution operator (::) to access a global variable if we have a local variable with the same name.
Can 2 global variable have same name?In other words, all global variables with the same name will be converted to be one variable - so your int a; and int a = 25; will be referring to the same int -sized piece of memory. Formally called tentative definition in C.
|