Golbal and local variable

Local Variable:

A local variable is a variable that is declared inside of a function or loop. When we define a variable within a function, its scope is limited to the function. This is the case with functions. From the time it is defined until the function’s conclusion, it is accessible. It will endure while the function is running. Access to local variables from outside the function is prohibited. The function’s parameter names have the same behavior as local variables.

Example:

def sum():

      a=10 #local variable cannot be accessed outside the function

      b=20

      sum=a+b

      print( sum)

print(a) #this gives an error

It will give you an error if you attempt to access variable “a” outside of the function. It can only be accessed within the function.

Globe variable:

A global variable, on the other hand, is simpler to comprehend because it is accessible throughout the program and is not specified inside the function. It can alternatively be described as a variable that is defined in the program’s main body. Any loop or function may call it. Anywhere in the software is within its scope.

Example:

a=1  #global variable

def print_Number():

            a=a+1;

            print(a)

 print_number()

This is due to the fact that we can only access the global variable; inside the function, we are unable to change it.

The global keyword in Python enables us to change the global variable. It is employed to establish a global variable and make local changes to the variable.

Rules of the global keyword:

Unless specifically designated as global, any value we assigned to a variable within the body of a function would be considered local Implicitly global variables are those that are exclusively used inside of functions. The global keyword shouldn’t be used outside of functions.

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in