Table of Contents
Example Description
Learn how to access global and local variables in Python, and understand the concept of variable scope. See an example code and explanation.

Introduction:

In Python, variable scope refers to the accessibility of variables within different parts of a program. There are two types of variable scope: global and local. Global variables are accessible throughout the entire program, while local variables are only accessible within a specific function or block of code.

Code:

#To access any variable outside the function
num = 5

def myFunc1( ):
 y = num + 5
 print("Accessing num -> (global) in myFunc1, value = ",num)
 print("Accessing y-> (local variable of myFunc1) accessible, value=",y)
#function call myFunc1()
myFunc1()

print("Accessing num outside myFunc1 ",num)
print("Accessing y outside myFunc1 ",y)

Logic:

  1. Declare a global variable “num” and assign it a value of 5.
  2. Define a function called myFunc1().
  3. Inside myFunc1(), declare a local variable “y” and assign it the value of “num” plus 5.
  4. Print the values of “num” and “y” inside myFunc1().
  5. Call myFunc1().
  6. Print the values of “num” and “y” outside of myFunc1().

Output:

>> Accessing num -> (global) in myFunc1, value = 5

>> Accessing y-> (local variable of myFunc1) accessible, value= 10

>> Accessing num outside myFunc1 5

Note: NameError: name ‘y’ is not defined, because num is a global variable defined outside and y is a local variable that is defined inside user defined function – myFunc1()