In the previous tutorial, we learned that what are global variables, local variables and nonlocal variables. And how to use them.
Global Keyword in Python
In this post, we will learn what is the global keyword in Python. What are the rules for writing this and how do you use the global keyword in Python programs.
What is global keyword in python
In Python, it is used to create a global variable. And also you can modify variables outside the current scope.
As you know, we cannot change the value of the global variable inside a function. If you don’t know, read this. But if you use the global keyword, then you can also change the value of the global variable inside the function.
Rules to write a global keyword in python
Following are the rules for writing global keywords in Python:
- When writing a variable inside a function. So that is the local variable.
- If you define a variable outside the function, it is a global variable. For this you do not need global keywords.
- If you want to define a global variable inside the function, then you have to use the global keyword.
- Use of global keywords outside a function has no effect
Using global keyword in python
Example 1: Accessing global Variable From Inside a Function
a = 1 # global variable def myFunc(): print(a) myFunc()
First we defined a global variable in the program named a. After this we assigned = = 1 to this variable.
After this we created a function called myFunc (). Inside this function, we called the global variable.
After that we called this function from which we got some output which is given below.
Output
1
Example 2: Modify Global Variable From Inside a Function using global keyword
a = 0 # global variable def myFunc(): global a a = a + 2 # increment by 2 print("Inside add():", a) myFunc() print("In main:", a)
First we defined a global variable in the program named a. After this we assigned = = 1 to this variable.
After this we created a function called myFunc (). Inside this function, we modified the value of the global variable by using the global keyword.
After that we called this function from which we got some output which is given below.
Output
Inside add(): 2 In main: 2
Note:- If you want to change the value of the global variable inside the function, then you have to use the global keyword for this. We will give an example of changing the value of a global variable.
In this post, you have learned how to change the value of the global variables by using the global keyword.