Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

Local variable vs. Global variable in Python

J Sai Jahnavi

A variable’s location is where the variable has been created and can be accessed. If a variable has been declared at one part of the program, it may not be accessed in another part of the program.

In Python, a variable has two types of scopes. These types are listed below.

Local variable

The Local Variable is where variables are defined inside the function.

For example, the code will throw an error because variable x is out of the scope in line 6, as seen below:

def print_number():
  x=10
  print("The first number is:",x)

print_number()
print("The first number is :",x)

In the above code, the ‘x’ variable is called by the print_number() function – We can print this. In contrast, when trying to print the same variable for the second time, it shows an error because it is outside the function and not a local variable. However, it was executed the first time because it was inside the variable.

Global variable

A Global Variable is where a variable is defined outside any function.

An example of this is:

a="scope variable"

def fun():
    print("Global variable is defined from:",a)

fun()

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring