Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """In Python, you can have multiple variables with the same name. Think
- of them as identical twins: their names look the same, but they are in
- fact two separate variables that can each contain their own value."""
- # This `spam` is a global variable. It was assigned outside of
- # all functions:
- spam = 'global'
- def func1():
- # This `spam` is a local variable because it was assigned inside
- # this function:
- spam = 'local'
- print(spam)
- def func2(spam):
- # This `spam` is a local variable. All parameters are local:
- print(spam)
- def func3():
- # This `spam` is the global variable, since no `spam` was assigned
- # in this function:
- print(spam)
- def func4():
- # This causes an error. `spam` was assigned in this function, making
- # it local, but the variable was used before it was assigned:
- print(spam) # THIS IS NOT THE GLOBAL `spam`.
- spam = 'local' # This assignment makes `spam` in this function local.
- # In this case, think of it as Python checking all the code in the
- # function first before running it to see which variables are
- # global and which are local.
- def func5():
- # It doesn't matter where the assignment is. If any assignment
- # statement exists in the function, the variable is local.
- # The code in this `if` block never runs, but that doesn't matter.
- # The `spam` variable here is still local.
- if False:
- spam = 'local' # This assignment makes `spam` in this function local.
- print(spam) # This causes an error since local `spam` wasn't defined.
- def func6():
- # This `spam` is global, even though it's assigned in this function,
- # because of the global statement:
- global spam
- print(spam)
- # This assigment doesn't make `spam` local because of the
- # global statement:
- spam = 'global'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement