Variable scope in Python: Difference between revisions
No edit summary |
|||
(2 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
[[File:idea.png|right|frame|This is basic programming knowledge]] | [[File:idea.png|right|frame|This is basic programming knowledge <ref>http://www.flaticon.com/</ref>]] | ||
==Introduction== | ==Introduction== | ||
Line 35: | Line 35: | ||
print(d) | print(d) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==References== | ==References== | ||
Line 70: | Line 42: | ||
[[Category:This information is incomplete]] | [[Category:This information is incomplete]] | ||
[[Category:Python]] | [[Category:Python]] | ||
[[Category: | [[Category:Variables]] | ||
[[Category:Scope]] |
Latest revision as of 08:46, 17 March 2016
Introduction[edit]
Recall that a variable is a label for a location in memory. It can be used to hold a value. In statically typed languages, variables have predetermined types, and a variable can only be used to hold values of that type. In Python, we may reuse the same variable to store values of any type.
A variable is similar to the memory functionality found in most calculators, in that it holds one value which can be retrieved many times, and that storing a new value erases the old. A variable differs from a calculator’s memory in that one can have many variables storing different values, and that each variable is referred to by name. [2]
Example of variable scope in Python[edit]
# This is a global variable
a = 0
if a == 0:
# This is still a global variable
b = 1
def my_function(c):
# this is a local variable
d = 3
print(c)
print(d)
# Now we call the function, passing the value 7 as the first and only parameter
my_function(7)
# a and b still exist
print(a)
print(b)
# c and d don't exist anymore -- these statements will give us name errors!
print(c)
print(d)