DEV Community

yugalakshmi
yugalakshmi

Posted on

Local and Global Variables in Python

  1. Local Variable

A local variable is declared inside a function. It can be accessed only within that function.

Example:

def eat(amount):
total = 500
return total - amount

print(eat(100))

Output:

400

Here, total and amount are local to the function.

  1. Global Variable

A global variable is declared outside a function. It can be accessed inside different functions.

Example:

total = 100000

def eat(amount):
return total - amount

print(eat(500))

Output:

99500

Here, total is a global variable and amount is a local parameter.

  1. Global Keyword

The global keyword is used to modify a global variable inside a function.

Example:

total = 100

def update():
global total
total = 500

update()
print(total)

Output:

500

Here, the global keyword allows us to modify the global variable total.

  1. Local and Global Variables in Function Calling

When we call a function inside another function, the variables do not automatically become global.

Example:

total = 100

def check(no1):
print(total - no1)

print(total)
check(10)

Output:

100
90

Top comments (0)