Difference Between Global and Local Variables in Python
Global Variables:
Global variables are those variables that are defined in the main body of the program file. They are visible throughout the program file.
Example:
pi = 3.142 radius = 7 def circle(): global radius # radius is a global variable radius = radius * 2 area_of_circle = pi * (radius) ** 2 print("The area of the circle is: ", area_of_circle)
Local Variables:
A variable which is defined within a function is called Local Variables. It can be accessed from the point of its definition until the end of the function in which it is defined.
Example:
pi = 3.142 # local variable radius = 7 # local variable area_of_circle = 0 area_of_circle = pi * (radius) ** 2 print("The area of the circle is: ", area_of_circle)
Global Variable vs Local Variable:
Global Variables | Local Variables |
1. It defines in the main body of the program file. | 1. It defines within a function and it is local to that function. |
2. It can be accessed throughout the program file. | 2. It can be accessed from the point of its definition until the end of the block in which it is defined. |
3. Global variables are accessible to all functions in the program. | 3. It's not related in any way to other variables with the same names are used outside the function. |