Understanding Local vs Global Variables in Python
Q: Can you explain the difference between local and global variables in Python? Can you provide an example?
- Python
- Mid level question
Explore all the latest Python interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Python interview for FREE!
x = 10 # global variable def func(): y = 5 # local variable print("x inside function:", x) # accessing global variable print("y inside function:", y) # accessing local variable func() print("x outside function:", x) # accessing global variable print("y outside function:", y) # this will result in an error, y is not defined outside the function
In this example, x is a global variable that is defined outside the function. Inside the function, y is a local variable that is defined and used only inside the function. When func() is called, it prints the values of both x and y. When the function returns, the y variable is destroyed, but the x variable continues to exist and can be accessed outside the function.


