Page 519 - ComputerScience_Class_11
P. 519

SCOPE OF VARIABLES
                 In Python, the scope of a variable refers to the part of the program where the variable is accessible. The two main types
                 of variable scope are local scope and global scope. Understanding these concepts is crucial for managing variables
                 effectively and ensuring that your code behaves as expected.


                 Local Variables
                 A local variable is a variable that is defined inside a function and can only be accessed within that function. It is
                 not accessible outside the function. Local variables are created when the function is called and destroyed when the
                 function finishes executing.
                 Syntax of a local variable:

                 def function_name():
                     local_variable = value # Local variable inside the function
                     # Code using the local variable
                 Where:
                 •  local_variable is the variable defined inside the function.

                 Program 4: Write a program to calculate the sum of even numbers within a given range using local variables.

                     Program 4.py
                  File  Edit  Format   Run   Options   Window     Help

                  def sum_even(start, end):
                      even_sum = 0 # Local variable for sum of even numbers

                      for num in range(start, end + 1):
                          if num % 2 == 0:
                              even_sum += num

                      print("Sum of even numbers:", even_sum)

                  sum_even(1, 10)




                     Output

                  Sum of even numbers: 30




                 Global Variables
                 A global variable is a variable that is defined outside any function and can be accessed from any part of the program,
                 including inside functions. Global variables are created when the program starts and exist until the program ends.
                 Syntax of a global variable:

                 global_variable = value # Global variable defined outside the function
                 def function_name():
                     # Code using the global variable
                 Where:
                 •  global_variable is defined outside any function and can be accessed anywhere in the program.



                                                                              For Advance Learners: Functions in Python  517
   514   515   516   517   518   519   520   521   522   523   524