Introduction:
In Python, we can declare variables as global so that they can be accessed and updated outside of functions. This allows us to use variables across different scopes within a program. In this code example, we demonstrate how to use the “global” keyword to access and update a global variable.
Code:
#To access any variable outside the function
num = 5
def myfunc1():
#Prefixing global informs Python to use the updated global
#variable num outside the function
global num
print("Accessing num =",num)
num = 10
print("num reassigned =",num)
#function ends here
myfunc1()
print("Accessing num outside myfunc1",num)
Logic:
- We start by declaring a global variable “num” and assigning it a value of 5.
- We define a function “myfunc1”.
- Inside the function, we use the “global” keyword to inform Python that we want to use the global variable “num”.
- We print the value of “num” inside the function, which is initially 5.
- We update the value of “num” to 10.
- We print the updated value of “num” inside the function
Output:
>> Accessing num = 5
>> num reassigned = 10
>> Accessing num outside myfunc1 10