Title: An Introduction to the Python Programming Language
1An Introduction to the Python Programming Language
- Presented by
- Michael DiRamio
- madiramio_at_gmail.com
2My Background
- At Brock for teachers college
- Currently on a practical teaching block at
Westlane Secondary (DSBN) - Undergrad at UW in math and computers with a
focus on programming languages - Favorite programming language is Scheme (my
apologies if I refer to it too often!)
3Your Background
- Which of these languages do you know?
- C or C
- Java
- Perl
- Scheme
4Presentation Overview
- Running Python and Output
- Data Types
- Input and File I/O
- Control Flow
- Functions
- Classes
5Hello World
- Open a terminal window and type python
- If on Windows open a Python IDE like IDLE
- At the prompt type hello world!
gtgtgt 'hello world!' 'hello world!'
6Python Overview
- From Learning Python, 2nd Edition
- Programs are composed of modules
- Modules contain statements
- Statements contain expressions
- Expressions create and process objects
7The Python Interpreter
- Python is an interpreted language
- The interpreter provides an interactive
environment to play with the language - Results of expressions are printed on the screen
gtgtgt 3 7 10 gtgtgt 3 lt 15 True gtgtgt 'print
me' 'print me' gtgtgt print 'print me' print me gtgtgt
8Output The print Statement
- Elements separated by commas print with a space
between them - A comma at the end of the statement (print
hello,) will not print a newline character
gtgtgt print 'hello' hello gtgtgt print 'hello',
'there' hello there
9Documentation
The starts a line comment
gtgtgt 'this will print' 'this will print' gtgtgt
'this will not' gtgtgt
10Variables
- Are not declared, just assigned
- The variable is created the first time you assign
it a value - Are references to objects
- Type information is with the object, not the
reference - Everything in Python is an object
11Everything is an object???
- Everything means everything, including functions
and classes (more on this later!)
gtgtgt x 7 gtgtgt x 7 gtgtgt x 'hello' gtgtgt
x 'hello' gtgtgt
Type info is with the object
12Numbers Integers
- Integer the equivalent of a C long
- Long Integer an unbounded integer value. Newer
versions of Python will automatically convert to
a long integer if you overflow a normal one
gtgtgt 132224 132224 gtgtgt 132323
2 17509376329L gtgtgt
13Numbers Floating Point
- int(x) converts x to an integer
- float(x) converts x to a floating point
- The interpreter shows a lot of digits, including
the variance in floating point - To avoid this use print
gtgtgt 1.23232 1.2323200000000001 gtgtgt print
1.23232 1.23232 gtgtgt 1.3E7 13000000.0 gtgtgt
int(2.0) 2 gtgtgt float(2) 2.0
14Numbers Complex
- Built into Python
- Same operations are supported as integer and float
gtgtgt x 3 2j gtgtgt y -1j gtgtgt x y (31j) gtgtgt x
y (2-3j)
15Numbers A Wrap Up
- Numbers are immutable
- Many math functions in the math module
gtgtgt import math gtgtgt dir(math) '__doc__',
'__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e',
'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot',
'ldexp', 'log', 'log10', 'modf', 'pi', 'pow',
'radians', 'sin', 'sinh', 'sqrt', 'tan',
'tanh' gtgtgt
16String Literals
- Strings are immutable
- There is no char type like in C or Java
- is overloaded to do concatenation
gtgtgt x 'hello' gtgtgt x x ' there' gtgtgt x 'hello
there'
17String Literals Many Kinds
- Can use single or double quotes, and three double
quotes for a multi-line string
gtgtgt 'I am a string' 'I am a string' gtgtgt "So am
I!" 'So am I!' gtgtgt """And me too! ... though I am
much longer ... than the others )""" 'And me
too!\nthough I am much longer\nthan the others )'
18Substrings and Methods
- len(String) returns the number of characters in
the String - str(Object) returns a String representation of
the Object
gtgtgt s '012345' gtgtgt s3 '3' gtgtgt
s14 '123' gtgtgt s2 '2345' gtgtgt
s4 '0123' gtgtgt s-2 '4'
gtgtgt len(x) 6 gtgtgt str(10.3) '10.3'
19String Formatting
- Similar to Cs printf
- ltformatted stringgt ltelements to insertgt
- Can usually just use s for everything, it will
convert the object to its String representation.
gtgtgt "One, d, three" 2 'One, 2, three' gtgtgt "d,
two, s" (1,3) '1, two, 3' gtgtgt "s two s"
(1, 'three') '1 two three' gtgtgt
20Lists
- Ordered collection of data
- Data can be different types
- Lists are mutable
- Issues with shared references and mutability
- Same subset operations as Strings
gtgtgt x 1,'hello', (3 2j) gtgtgt x 1, 'hello',
(32j) gtgtgt x2 (32j) gtgtgt x02 1, 'hello'
21Lists Modifying Content
gtgtgt x 1,2,3 gtgtgt y x gtgtgt x1 15 gtgtgt x 1,
15, 3 gtgtgt y 1, 15, 3 gtgtgt x.append(12) gtgtgt
y 1, 15, 3, 12
- xi a reassigns the ith element to the value a
- Since x and y point to the same list object, both
are changed - Append also modifies the list
22Lists not all are in-place changes
gtgtgt x 1,2,3 gtgtgt y x gtgtgt z
x.append(12) gtgtgt z None True gtgtgt y 1, 2, 3,
12 gtgtgt x x 9,10 gtgtgt x 1, 2, 3, 12, 9,
10 gtgtgt y 1, 2, 3, 12 gtgtgt
- Append modifies the list and returns None (the
python version of null) - List addition returns a new list
23Tuples
- Tuples are immutable versions of lists
- One strange point is the format to make a tuple
with one element (the , is needed to
differentiate from the mathematical expression (2)
gtgtgt x (1,2,3) gtgtgt x1 (2, 3) gtgtgt y (2,) gtgtgt
y (2,) gtgtgt
24Dictionaries
- A set of key-value pairs
- Dictionaries are mutable
gtgtgt d 1 'hello', 'two' 42, 'blah'
1,2,3 gtgtgt d 1 'hello', 'two' 42, 'blah'
1, 2, 3 gtgtgt d'blah' 1, 2, 3
25Dictionaries Add/Modify
- Entries can be changed by assigning to that entry
- Assigning to a key that does not exist adds an
entry
gtgtgt d 1 'hello', 'two' 42, 'blah' 1, 2,
3 gtgtgt d'two' 99 gtgtgt d 1 'hello', 'two'
99, 'blah' 1, 2, 3 gtgtgt d7 'new entry'
gtgtgt d 1 'hello', 7 'new entry', 'two' 99,
'blah' 1, 2, 3
26Dictionaries Deleting Elements
- The del method deletes an element from a
dictionary
gtgtgt d 1 'hello', 2 'there', 10 'world' gtgtgt
del(d2) gtgtgt d 1 'hello', 10 'world'
27Copying Dictionaries and Lists
- The built-in list function will copy a list
- The dictionary has a method called copy
gtgtgt l1 1 gtgtgt l2 list(l1) gtgtgt l10 22 gtgtgt
l1 22 gtgtgt l2 1
gtgtgt d 1 10 gtgtgt d2 d.copy() gtgtgt d1
22 gtgtgt d 1 22 gtgtgt d2 1 10
28Data Type Wrap Up
- Lists, Tuples, and Dictionaries can store any
type (including other lists, tuples, and
dictionaries!) - Only lists and dictionaries are mutable
- All variables are references
29Data Type Wrap Up
- Integers 2323, 3234L
- Floating Point 32.3, 3.1E2
- Complex 3 2j, 1j
- Lists l 1,2,3
- Tuples t (1,2,3)
- Dictionaries d hello there, 2 15
30Input
- The raw_input(string) method returns a line of
user input as a string - The parameter is used as a prompt
- The string can be converted by using the
conversion methods int(string), float(string),
etc.
31Input Example
print "What's your name?" name
raw_input("gt") print "What year were you
born?" birthyear int(raw_input("gt")) print "Hi
s! You are d years old!" (name, 2005 -
birthyear)
python input.py What's your name? gtMichael What
year were you born? gt1980 Hi Michael! You are 25
years old!
32Files Input
33Files Output
34Booleans
- 0 and None are false
- Everything else is true
- True and False are aliases for 1 and 0
respectively (added in more recent versions of
Python)
35Boolean Expressions
- Compound boolean expressions short circuit
- and and or return one of the elements in the
expression - Note that when None is returned the interpreter
does not print anything
gtgtgt True and False False gtgtgt False or
True True gtgtgt 7 and 14 14 gtgtgt None and 2 gtgtgt None
or 2 2
36Moving to Files
- The interpreter is a good place to try out some
code, but what you type is not reusable - Files can be read into the interpreter using the
import statement
37If Statements
x 22 if x lt 15 print 'first clause' elif
x lt 25 print 'second clause' else
print 'the else'
gtgtgt import ifstatement second clause gtgtgt
In interpreter
In file ifstatement.py
38No Braces???
- Python uses indentation instead of braces to
determine the scope of expressions - All lines must be indented the same amount to be
part of the scope (or indented more if part of an
inner scope) - This forces the programmer to use proper
indentation since the indenting is part of the
program!
39While Loops
gtgtgt import whileloop 1 2 3 4 5 6 7 8 9 gtgtgt
x 1 while x lt 10 print x x x 1
In whileloop.py
In interpreter
40Loop Control Statements
41The Loop Else Clause
- The optional else clause runs only if the loop
exits normally (not by break)
x 1 while x lt 3 print x x x
1 else print 'hello'
python whileelse.py 1 2 hello
Run from the command line
In whileelse.py
42The Loop Else Clause
x 1 while x lt 5 print x x x 1
break else print 'i got here'
python whileelse2.py 1
whileelse2.py
43For Loops
- Similar to perl forloops, iterating through a
list of values - Forloops also have the optional else clause
python forloop.py 1 7 13 2
for x in 1,7,13,2 print x
forloop.py
44Function Basics
gtgtgt import functionbasics gtgtgt max(3,5) 5 gtgtgt
max('hello', 'there') 'there' gtgtgt max(3,
'hello') 'hello'
def max(x,y) if x lt y return x
else return y
45Function Not-So-Basics
- Functions are first class objects
- Can be assigned to a variable
- Can be passed as a parameter
- Can be returned from a function
- Functions are treated like any other variable in
python, the def statement simply assigns a
function to a variable
46Functions as Variables
gtgtgt x 10 gtgtgt x 10 gtgtgt def x () ... print
'hello' gtgtgt x ltfunction x at 0x619f0gt gtgtgt
x() hello gtgtgt x 'blah' gtgtgt x 'blah'
- Functions are objects
- The same reference rules hold for them as for
other objects
47Functions As Parameters
def foo(f, a) return f(a) def bar(x)
retun x x
gtgtgt from funcasparam import gtgtgt foo(bar, 3) 9
- The function foo takes two parameters and applies
the first as a function with the second as its
parameter
48Functions In Functions
- Since they are like any other object, you can
have functions inside functions
def foo (x,y) def bar (z) return
z 2 return bar(x) y
gtgtgt from funcinfunc import gtgtgt foo(2,3) 7
49Functions Returning Functions
def foo (x) def bar(y) return x
y return bar main f foo(3) print
f print f(2)
python funcreturnfunc.py ltfunction bar at
0x612b0gt 5
50Parameters Defaults
- Can assign default values to parameters
- They are overridden if a parameter is given for
them - The type of the default doesnt limit the type of
a parameter
gtgtgt def foo(x 3) ... print x ... gtgtgt
foo() 3 gtgtgt foo(10) 10 gtgtgt foo('hello') hello
51Parameters Named
- Can specify the name of the parameter to set
- Any positional arguments must come before named
ones in a call
gtgtgt def foo (a,b,c) ... print a, b, c ...
gtgtgt foo(c 10, a 2, b 14) 2 14 10 gtgtgt
foo(3, c 2, b 19) 3 19 2
52Anonymous Functions
- The lambda returns a function
- The body can only be a simple expression, not
complex statements
gtgtgt f lambda x,y x y gtgtgt f(2,3) 5 gtgtgt l
'one', lambda x x x, 3 gtgtgt l1(4) 16
53Classes
- A collection of data and methods that act on that
data - But in python functions are basically just data!
54Class Syntax
class myclass def __init__(self, val)
self.x val def printit(self)
print self.x
- Every method in a class takes a self-pointer as
the first parameter (self as convention) like
this in java or C - __init__ is a builtin function that you override
as the constructor
gtgtgt from classbasic import gtgtgt x
myclass(3) gtgtgt x.printit() 3
55Class Method Calls
- Self is automatically added as the first
parameter when a method is called on an instance
of a class - Internally self must be explicitly passed
56Class Inheritance
- Super classes are listed in brackets after the
name of the class - Python allows multiple inheritance
- Name resolution is bottom to top, left to right
57Class Inheritance Example
class c1 x 10 class c2 x
20 y 15 class c3(c1,c2) z 2
gtgtgt from classinherit import gtgtgt x c3() gtgtgt
obj c3() gtgtgt obj.z 2 gtgtgt obj.x 10 gtgtgt obj.y 15
58Explicit Call to a Super-class Method
class c1 def __init__(self, x)
self.x x def foo(self) print
self.x
class c2 (c1) def __init__(self, x, y)
c1.__init__(self, x) self.y
y def foo(self) c1.foo(self)
print self.y
gtgtgt obj c2(4,5) gtgtgt obj.foo() 4 5
59Instance Variables
- Created as they are assigned
- Referenced as self.ltvariablegt
60Classes as Objects
- Classes exist as objects and contain all of there
own variables - Name resolution starts looking in the instance of
the class for a variable, then walks up the
inheritance tree - Variables dont exist in the instance until they
are assigned there
61Classes as Objects Example
gtgtgt class myclass ... x 10 ... gtgtgt a
myclass() gtgtgt b myclass() gtgtgt a.x, b.x,
myclass.x (10, 10, 10) gtgtgt a.x 15 gtgtgt a.x, b.x,
myclass.x (15, 10, 10)
gtgtgt myclass.x 20 gtgtgt a.x, b.x, myclass.x (15,
20, 20) gtgtgt a.x myclass.x gtgtgt a.x, b.x,
myclass.x (20, 20, 20) gtgtgt myclass.x 99 gtgtgt
a.x, b.x, myclass.x (20, 99, 99)
62Docstrings
- triple-quote strings at the beginning of an
object - Creates the __doc__ variable of the object
"""docstring of module""" class myclass
"""A class that really does nothing
but demonstrate docstrings""" def foo ()
"""and a useless method for the same
purpose""" print 'hi
63Docstrings Example
gtgtgt import docstrings gtgtgt docstrings.__doc__ 'docs
tring of module' gtgtgt docstrings.myclass.__doc__ 'A
class that really does nothing but\ndemonstrate
docstrings' gtgtgt docstrings.myclass.foo.__doc__ 'an
d a useless method for the same purpose'
64Modules
- The highest level structure of Python
- Each file is a module
- Each has its own namespace
65Modules Imports
66Useful Sources
- I used the following in preparation of this
presentation - Learning Python, 2nd Edition
- Python in a Nutshell
- www.python.org