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:
- Declare a global variable “num” and assign it a value of 5.
- Define a function called myFunc1().
- Inside myFunc1(), declare a local variable “y” and assign it the value of “num” plus 5.
- Print the values of “num” and “y” inside myFunc1().
- Call myFunc1().
- 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()