Advertisement
asweigart

Untitled

Oct 21st, 2019
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. """In Python, you can have multiple variables with the same name. Think
  2. of them as identical twins: their names look the same, but they are in
  3. fact two separate variables that can each contain their own value."""
  4.  
  5. # This `spam` is a global variable. It was assigned outside of
  6. # all functions:
  7. spam = 'global'
  8.  
  9. def func1():
  10. # This `spam` is a local variable because it was assigned inside
  11. # this function:
  12. spam = 'local'
  13. print(spam)
  14.  
  15. def func2(spam):
  16. # This `spam` is a local variable. All parameters are local:
  17. print(spam)
  18.  
  19. def func3():
  20. # This `spam` is the global variable, since no `spam` was assigned
  21. # in this function:
  22. print(spam)
  23.  
  24. def func4():
  25. # This causes an error. `spam` was assigned in this function, making
  26. # it local, but the variable was used before it was assigned:
  27. print(spam) # THIS IS NOT THE GLOBAL `spam`.
  28. spam = 'local' # This assignment makes `spam` in this function local.
  29.  
  30. # In this case, think of it as Python checking all the code in the
  31. # function first before running it to see which variables are
  32. # global and which are local.
  33.  
  34. def func5():
  35. # It doesn't matter where the assignment is. If any assignment
  36. # statement exists in the function, the variable is local.
  37. # The code in this `if` block never runs, but that doesn't matter.
  38. # The `spam` variable here is still local.
  39. if False:
  40. spam = 'local' # This assignment makes `spam` in this function local.
  41. print(spam) # This causes an error since local `spam` wasn't defined.
  42.  
  43. def func6():
  44. # This `spam` is global, even though it's assigned in this function,
  45. # because of the global statement:
  46. global spam
  47. print(spam)
  48. # This assigment doesn't make `spam` local because of the
  49. # global statement:
  50. spam = 'global'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement