Back to community
Computer ScienceClass 11 (CBSE)

What is the difference between local and global variables in Python functions?

I changed a variable inside a function but outside the function it still showed the old value. My teacher mentioned scope but I did not fully follow. Can someone explain?

Asked by Ananya Sharma 17 45d ago
Need a Computer Science tutor? Browse verified Computer Science tutors near you.

1 answer

1

Scope decides where a variable can be seen and used. A local variable is created inside a function and exists only there; once the function ends, it disappears, and code outside cannot use it. A global variable is created outside all functions and can be read anywhere in the program. When you assign to a variable inside a function, Python treats it as a new local variable by default, which is why your outside value did not change, you were actually editing a separate local copy. If you genuinely need to modify the global one inside the function, declare 'global varname' at the top of the function. As good practice, though, prefer passing values in as parameters and returning results, rather than relying on global variables.

D
Deepak Kulkarni
355 pts· 45d ago

Sign in as a tutor to answer this doubt.