Sitemap

Global And Local Variable

Jun 2, 2026

--

# local variable — A variable that is defined inside a function and can only be accessed within that function.

example1-

def greet():

name = “sapna” #local variable

print(“hello”,name)

greet()

output will be- hello sapna.

Example 2-

def greet():

Get Techsolutionsold’s stories in your inbox

Join Medium for free to get updates from this writer.

msg = “Hello!”

print(“Inside function:”, msg) # this will print -inside function: Hello!

greet()

print(“Outside function:”, msg) # this will give an error because msg is a local variable and cannot be accessed outside the function.

# Global variable — A variable that is defined outside of any function and can be accessed from anywhere in the code.

Example2 -

name =”Rahul” #global variable

def greet():

print(“hello”,name)

greet()

#the output will be -this will give the output because name is a global variable and can be accessed inside the function.

--

--