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 num is set to 9.

    • doubleNum is a local variable defined in double.

    • Calculates double value: doubleNum = num * 2.

    • The function prints this value but does not affect the original num in main.

Main Function Behavior

  • Function Calling:

    • main() calls double(num) where num remains 9 after the function call.

    • The changes inside the double function only affect the local doubleNum variable, not num.


Global Variables in Action

  • Global Declaration: varForAll = 100

    • Can be accessed anywhere in the program.

  • Function Example: def funct1():

    • Local variables declared (e.g., funct1var set to 5) are only accessible inside funct1.

    • 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-declare varForAll as 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 global to access and modify a global variable inside a function without overshadowing it:

    • global varForAll allows 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.