0% found this document useful (0 votes)
41 views

Local Variables Cannot Be Used in The Global Scope: Spam Spam

Scopes determine where variables can be accessed in Python. Local variables defined inside a function can only be used within that function and not in the global scope, while global variables defined outside of functions can be accessed from any scope. Using local variables rather than global ones helps narrow down where bugs may occur by limiting variable modifications to the code within each function.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Local Variables Cannot Be Used in The Global Scope: Spam Spam

Scopes determine where variables can be accessed in Python. Local variables defined inside a function can only be used within that function and not in the global scope, while global variables defined outside of functions can be accessed from any scope. Using local variables rather than global ones helps narrow down where bugs may occur by limiting variable modifications to the code within each function.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

not remember the values stored in them from the last time the function

was called. Local variables are also stored in frame objects on the call
stack.
Scopes matter for several reasons:

Code in the global scope, outside of all functions, cannot use any
local variables.
However, code in a local scope can access global variables.
Code in a function’s local scope cannot use variables in any other
local scope.
You can use the same name for different variables if they are in
different scopes. That is, there can be a local variable named spam
and a global variable also named spam.

The reason Python has different scopes instead of just making


everything a global variable is so that when variables are modified by the
code in a particular call to a function, the function interacts with the
rest of the program only through its parameters and the return value.
This narrows down the number of lines of code that may be causing a
bug. If your program contained nothing but global variables and had a
bug because of a variable being set to a bad value, then it would be hard
to track down where this bad value was set. It could have been set from
anywhere in the program, and your program could be hundreds or
thousands of lines long! But if the bug is caused by a local variable with
a bad value, you know that only the code in that one function could
have set it incorrectly.
While using global variables in small programs is fine, it is a bad
habit to rely on global variables as your programs get larger and larger.

Local Variables Cannot Be Used in the Global Scope


Consider this program, which will cause an error when you run it:

def spam():
➊ eggs = 31337
spam()
print(eggs)

You might also like