Variable scope in Python: Difference between revisions

From Computer Science Wiki
No edit summary
No edit summary
 
Line 35: Line 35:
print(d)
print(d)
</syntaxhighlight>
</syntaxhighlight>
== List of possible exceptions ==
[http://www.tutorialspoint.com/python/python_exceptions.htm Please click here for a list of exceptions]


==References==
==References==
Line 46: Line 42:
[[Category:This information is incomplete]]
[[Category:This information is incomplete]]
[[Category:Python]]
[[Category:Python]]
[[Category:Exceptions]]
[[Category:Variables]]
[[Category:Scope]]

Latest revision as of 09:46, 17 March 2016

This is basic programming knowledge [1]

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)

References[edit]