Variable scope in Python: Difference between revisions

From Computer Science Wiki
Line 35: Line 35:
print(d)
print(d)
</syntaxhighlight>
</syntaxhighlight>
In the example above, if a user enters a string, for example 'abc', python 2.7 would throw a NameError exception. This example was swiped from the official Python documentation which you should read.  <ref>https://docs.python.org/2/tutorial/errors.html</ref>
<syntaxhighlight lang="python" line="1" >
# this code will generate a TypeError. We cannot concatenate a string and integer.
my_age = 16
try:
    print("Your age is " + my_age) 
except TypeError:
    print("Hey. You should know better than to combine strings and integers!")
</syntaxhighlight>
In the example above, we have been silly and tried to concatenate a string and an integer! We are testing for a specific type of exception, TypeError.
<syntaxhighlight lang="python" line="1" >
my_age = 16
try:
    print("Your age is " + my_age) 
except Exception:
    print("Yikes. Something has gone horribly wrong.")
</syntaxhighlight>
In our final example, above, we are using a generic test for any possible exception.


== List of possible exceptions ==
== List of possible exceptions ==

Revision as of 09:43, 17 March 2016

This is basic programming knowledge

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. [1]

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)

List of possible exceptions[edit]

Please click here for a list of exceptions

References[edit]