Python tutorial | variables, function, arguments, Exceptions

This python programming tutorial covers variables, function, arguments and Exceptions.

Program Organization and Functions

We will cover following on this page:

How to organize larger programs,details on program execution,defining and working with functions and
exceptions and Error Handling.


What is a "Script?"

A "script" is a program that simply runs a series of statements and stops

# program.py

statement1
statement2
statement3
...


Program Structure

Recall: programs are a sequence of statements
height = 442 # Meters
thickness = 0.1*(0.001) # Meters (0.1 millimeter)


numfolds = 0
while thickness <= height:
thickness = thickness * 2
numfolds = numfolds + 1
print numfolds, thickness

print numfolds, "folds required"
print "final thickness is", thickness, "meters"

Programs run by executing the statements in the same order that they are listed.


Defining Things

You must always define things before they get used later on in a program.
a = 42
b = a + 2 # Requires that a is already defined

def square(x):
return x*x

z = square(b) # Requires square to be defined

The order is important
You almost always put the definitions of variables and functions near the beginning

Defining Functions

It is a good idea to put all of the code related to a single "task" all in one place
def read_prices(filename):
pricesDict = {}
for line in open(filename):
fields = line.split(',')
name = fields[0].strip('"')
pricesDict[name] = float(fields[1])
return pricesDict


A function also simplifies repeated operations
oldprices = read_prices("oldprices.csv")
newprices = read_prices("newprices.csv")


What is a function?

A function is a sequence of statements
def funcname(args):
statement
statement
...
statement
Any Python statement can be used inside
def foo():
import math
print math.sqrt(2)
help(math)
There are no "special" statements in Python


Function Definitions

Functions can be defined in any order
def foo(x):
bar(x)

def bar(x):
statements
Functions must only be defined before they are actually used during program execution
foo(3) # foo must be defined already
Stylistically, it is more common to see functions defined in a "bottom-up" fashion


Bottom-up Style

Functions are treated as building blocks
The smaller/simpler blocks go first
# myprogram.py
def foo(x):
...

def bar(x):
...

foo(x)
...

def spam(x):
...
bar(x)
...

spam(42) # Call spam() to do something


Functions can be redefined in python.
def foo(x):
return 2*x

print foo(2) # Prints 4

def foo(x,y): # Redefine foo(). This replaces
return x*y # foo() above.

print foo(2,3) # Prints 6
print foo(2) # Error : foo takes two arguments

A repeated function definition silently replaces the previous definition
No overloaded functions (vs. C++, Java).


Function Design

Functions should be easy to use
The whole point of a function is to define code for repeated operations
Some things to think about:
Function inputs and output
Side-effects

Function Arguments

Functions operate on passed arguments
def square(x):
return x*x

Argument variables receive their values when the function is called
a = square(3)

The argument names are only visible inside the function body (are local to function)

Default Arguments

Sometimes you want an optional argument
def read_prices(filename,delimiter=','):
...
If a default value is assigned, the argument is optional in function calls
d = read_prices("prices.csv")


Calling a Function

Consider a simple function
def read_prices(filename,delimiter=','):
...
Calling with "positional" args
prices = read_prices("prices.csv",",")

Keyword Arguments

Calling with "keyword" arguments
prices = read_prices(filename="price.csv",delimiter=",")
Here, you explicitly name and assign a value to each argument
Common use case : functions with many optional features
def sort(data,reverse=False,key=None):
statements

sort(s,reverse=True)

Mixed Arguments

Positional and keyword arguments can be mixed together in a function call
read_prices("prices.csv",delimiter=',')
The positional arguments must go first.
Basic rules:
All required arguments get values
No duplicate argument values

Return Values

return statement returns a value
def square(x):
return x*x
If no return value, None is returned
def bar(x):
statements
return

a = bar(4) # a = None

Return value is discarded if not assigned/used
square(4) # Calls square() but discards result

Multiple Return Values

A function may return multiple values by returning a tuple
def divide(a,b):
q = a // b # Quotient
r = a % b # Remainder
return q,r # Return a tuple

Usage examples:
x = divide(37,5) # x = (7,2)
x,y = divide(37,5) # x = 7, y = 2

Understanding Variables

Programs assign values to variables
x = value # Global variable

def foo():
y = value # Local variable

Variable assignments occur outside and inside function definitions
Variables defined outside are "global"
Variables inside a function are "local"

Local Variables

Variables inside functions are private
def read_portfolio(filename):
portfolio = []
for line in open(filename):
fields = line.split()
s = (fields[0],int(fields[1]),float(fields[2]))
portfolio.append(s)
return portfolio
Values not retained or accessible after return
>>> stocks = read_portfolio("stocks.dat")
>>> fields
Traceback (most recent call last):
File "", line 1, in ?
NameError: name 'fields' is not defined

Global Variables

Functions can access the values of globals
delimiter = ',�

def read_portfolio(filename):
...
for line in open(filename):
fields = line.split(delimiter)
...

Modifying Globals

One quirk: Functions can't modify globals
delimiter = ','

def set_delimiter(newdelimiter):
delimiter = newdelimiter

If you want to modify a global variable you must declare it as such in the function
delimiter = ','
def set_delimiter(newdelimiter):
global delimiter
delimiter = newdelimiter
global declaration must appear before use


More on Functions


Variable Arguments

Function that accepts any number of args
def foo(x,*args):
...
Here, the arguments get passed as a tuple
foo(1,2,3,4,5)

def foo(x,*args):

Example:
def print_headers(*headers):
for h in headers:
print "%10s" % h,
print
print ("-"*10 + " ")*len(headers)

Function that accepts any keyword args
def foo(x,y,**kwargs):
...
Extra keywords get passed in a dict
foo(2,3,flag=True,mode="fast",header="debug")

def foo(x,y,**kwargs):


Passing Tuples and Dicts

Tuples can be expand into function args
args = (2,3,4)
foo(1, *args) # Same as foo(1,2,3,4)
Dictionaries can expand to keyword args
kwargs = {
'color' : 'red',
'delimiter' : ',',
'width' : 400 }

foo(data, **kwargs)
# Same as foo(data,color='red',delimiter=',',width=400)

These are not commonly used except when writing library functions.

Error Checking

Python performs no checking or validation of function argument types or values
A function will work on any data that is compatible with the statements in the function
def add(x,y):
return x + y

If there are errors in a function, they will show up at run time (as an exception)
Example
def add(x,y):
return x+y


Python also performs no checking of function return values
Inconsistent use does not result in an error
def foo(x,y):
if x:
return x + y
else:
return

Exceptions

Used to signal errors

Raising an exception (raise)
if name not in names:
raise RuntimeError("Name not found")

Catching an exception (try)
try:
authenticate(username)
except RuntimeError,e:
print e

Exceptions propagate to first matching except
def foo():
try:
bar()
except RuntimeError,e:
...

def bar():
try:1
spam()
except RuntimeError,e:
...

def spam():
grok()

def grok():
...
raise RuntimeError("Whoa!")


There are many built-in exceptions in python as listed below:

ArithmeticError
AssertionError
EnvironmentError
EOFError
ImportError
IndexError
KeyboardInterrupt
KeyError
MemoryError
NameError
ReferenceError
RuntimeError
SyntaxError
SystemError
TypeError
ValueError

Exception Values

Most exceptions have an associated value
More information about what's wrong
raise RuntimeError("Invalid user name")
Passed to variable supplied in except
try:
...
except RuntimeError,e:
...
It's an instance of the exception type, but often looks like a string
except RuntimeError,e:
print "Failed : Reason", e


Catching Multiple Errors

Can catch different kinds of exceptions
try:
...
except LookupError,e:
...
except RuntimeError,e:
...
except IOError,e:
...
except KeyboardInterrupt,e:
...
Alternatively, if handling is same
try:
...
except (IOError,LookupError,RuntimeError),e:


Catching All Errors

Catching any exception
try:
...
except Exception:
print "An error occurred"

Ignoring an exception (pass)
try:
...
except RuntimeError:
pass...


finally statement

Specifies code that must run regardless of whether or not an exception occurs
lock = Lock()

lock.acquire()
try:
...
finally:
lock.release() # release the lock

It is commonly use to properly manage resources (especially locks, files, etc.).


Program Exit

Program exit is handle through exceptions
raise SystemExit
raise SystemExit(exitcode)

An alternative sometimes seen
import sys
sys.exit()
sys.exit(exitcode)
Catching keyboard interrupt (Control-C)
try:
statements
except KeyboardInterrupt:
statements

Similar posts on Python tutorial

Useful DSP codes in Python