Table of Contents

Accessing Updating Variables Outside Functions

Example Description
In Python, this code demonstrates how the global variables allow us to access and update their values outside of functions.

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:

  1. We start by declaring a global variable “num” and assigning it a value of 5.
  2. We define a function “myfunc1”.
  3. Inside the function, we use the “global” keyword to inform Python that we want to use the global variable “num”.
  4. We print the value of “num” inside the function, which is initially 5.
  5. We update the value of “num” to 10.
  6. We print the updated value of “num” inside the function

Output:

>> Accessing num = 5

>> num reassigned = 10

>> Accessing num outside myfunc1 10