Loading...
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?
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.
Sign in as a tutor to answer this doubt.