Page 521 - ComputerScience_Class_11
P. 521

Output

                  Local variable inside the function: 50
                  Global variable outside the function: 100




                 Difference Between Local and Global Variables
                 In Python, local variables and global variables are both used to store values, but they have different scopes and
                 lifetimes. Understanding the key differences between them is important for effectively managing variables in your
                 program.

                     Aspect                    Local Variable                              Global Variable

                 Scope          Accessible only within the function.        Accessible throughout the program.
                 Lifetime       Created and destroyed during function execution.  Exists as long as the program runs.
                 Access         Can only be accessed inside the function.   Can be accessed both inside and outside functions.
                 Modification   Cannot be modified outside the function.    Can be modified with global inside a function.

                 Memory         Takes memory only during function execution.  Occupies memory until the program ends.


                     RETURN STATEMENT IN FUNCTION
                 The return statement is used to send a result from a function back to the calling program. When a function reaches
                 a return statement, it stops executing and returns the specified value. This allows the function to provide output that
                 can be used elsewhere in the program.
                 Syntax of return statement:

                 def function_name():
                     # Code inside the function
                     return value # Return value to the caller
                 Where:
                 •  value is the result or data that the function returns to the caller.

                 •  once the return statement is executed, the function ends and the control is transferred back to where the function
                   was called.

                 Program 7: Write a program to check if a number is even or odd using a return statement.
                     Program 7.py

                  File  Edit  Format   Run   Options   Window     Help

                  def check_even_odd(number):
                      if number % 2 == 0:
                          return "Even"  # Return "Even" if the number is divisible by 2
                      else:
                          return "Odd"    # Return "Odd" if the number is not divisible by 2


                  result = check_even_odd(7)
                  print("The number is:", result)






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