Lecture-21 Local_Global var 24-25
COMP101: Introduction to Programming 2024-25 Lecture-21
Global and Local Variables
Overview
Understanding global and local variables is essential in programming.
Variables' scope determines where they can be accessed and modified in the program.
Scope of Variables
Definition of Scope: Scope refers to the visibility and lifetime of a variable in different parts of the program.
Global Variables
Declared outside any function.
Can be accessed from any part of the program.
Use with caution; overuse can lead to unexpected side effects.
Local Variables
Declared inside a function.
Can only be accessed and modified within that specific function.
Avoids unintended interactions with other parts of the program.
Local Variables in Action
Example Function:
def double(num):Parameter
numis set to9.doubleNumis a local variable defined indouble.Calculates double value:
doubleNum = num * 2.The function prints this value but does not affect the original
numinmain.
Main Function Behavior
Function Calling:
main()callsdouble(num)wherenumremains9after the function call.The changes inside the
doublefunction only affect the localdoubleNumvariable, notnum.
Global Variables in Action
Global Declaration:
varForAll = 100Can be accessed anywhere in the program.
Function Example:
def funct1():Local variables declared (e.g.,
funct1varset to5) are only accessible insidefunct1.Attempts to access local variables outside their function will cause errors.
Problems with Global Variables
Variable Overriding
Example:
First, declare a global variable
varForAll = 100.Inside
funct1(), if you re-declarevarForAllas a local variable:If not declared global, it shadows the global variable, leading to confusion.
Example output shows both the local and global accessing the same variable name but resulting in different values.
Accessing Global Variables
Use the keyword
globalto access and modify a global variable inside a function without overshadowing it:global varForAllallows access to the variable's global value.Incorrect use of variable names can lead to unintended modifications of global variables.
Recommendations
Best Practices:
Avoid using the same names for global and local variables.
Be explicit in declaring global variables when inside functions to prevent accidental reassignments.
Consider variable scope carefully to maintain clean and understandable code.