Page 520 - ComputerScience_Class_11
P. 520
Program 5: Write a program to demonstrate the use of a global variable inside a function.
Program 5.py
File Edit Format Run Options Window Help
# Global variable
counter = 0
def increment():
global counter # Declare that we are modifying the global variable
counter += 1
print("Counter inside function:", counter)
increment()
print("Counter outside function:", counter)
Output
Counter inside function: 1
Counter outside function: 1
Global and Local Variables with the Same Name
When a variable with the same name is defined both as a global variable and as a local variable inside a function,
Python will prioritize the local variable within the function's scope. The local variable will "shadow" the global variable,
meaning the value of the global variable will not be accessed inside the function and instead, the local variable's value
will be used.
If you try to access the global variable inside the function without using the global keyword, the local variable will be
referenced instead. To access the global variable inside the function, you would need to use the global keyword.
Program 6: Write a program to demonstrate the use of a global and local variables with the same name.
Program 6.py
File Edit Format Run Options Window Help
# Global variable
number = 100
# Define a function with a local variable having the same name
def display_number():
number = 50 # Local variable
print("Local variable inside the function:", number)
display_number()
print("Global variable outside the function:", number)
518 Touchpad Computer Science (Ver. 3.0)-XI

