Slide Pythonlearn
Slide Pythonlearn
Python Language
Programming Basics
v Code or source code: The sequence of instructions in a
program.
v object-oriented programming
v functional programming
Python overview
v Core design philosophy [The Zen of Python (PEP 20)]
Ø Beautiful is better than ugly.
Ø Readability counts.
Python interpreter
v Python is an interpreted
language
• When you make a mistake, the computer does not think you are “cute”. It says
“syntax error” - given that it knows the language and you are just learning it. It
seems like Python is cruel and unfeeling.
• You must remember that you are intelligent and can learn. The computer is
simple and very fast, but cannot learn. So it is easier for you to learn Python than
for the computer to learn English...
Talking to Python
csev$ python3
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType
"help", "copyright", "credits" or "license" for more information.
>>>
What
next?
csev$ python3
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType
"help", "copyright", "credits" or "license" for more information.
>>> x = 1
>>> print(x)
1
>>> x = x + 1 This is a good test to make sure that you have
>>> print(x) Python correctly installed. Note that quit() also
2 works to end the interactive session.
>>> exit()
What Do We Say?
Elements of Python
• Vocabulary / Words - Variables and Reserved words (Chapter 2)
• Sentence structure - valid syntax patterns (Chapters 3-5)
• Story structure - constructing a program for a purpose
name = input('Enter file:')
handle = open(name)
A short “story”
counts = dict()
for line in handle:
about how to count
words = line.split() words in a file in
for word in words:
counts[word] = counts.get(word,0) + 1
Python
bigcount = None python words.py
bigword = None
for word,count in counts.items():
Enter file: words.txt
if bigcount is None or count > bigcount: to 16
bigword = word
bigcount = count
print(bigword, bigcount)
Reserved Words
You cannot use reserved words as variable names / identifiers
x = 2 Assignment statement
x = x + 2 Assignment with expression
print(x) Print statement
• Most programs are much longer, so we type them into a file and tell
Python to run the commands in the file.
• Script
- You enter a sequence of statements (lines) into a file using a text
editor and tell Python to execute the statements in the file
Program Steps or Program Flow
• Like a recipe or installation instructions, a program is a sequence of
steps to be done in order.
print('Smaller') Program:
No Output:
x = 5
Yes if x < 10: Smaller
x > 20 ? print('Smaller') Finis
if x > 20:
print('Bigger') print('Bigger')
No
print('Finis')
print('Finis')
n=5 Repeated Steps
No Yes Output:
n>0? Program:
5
print(n) n = 5 4
while n > 0 :
print(n)
3
n = n -1 n = n – 1 2
print('Blastoff!') 1
Blastoff!
Loops (repeated steps) have iteration variables that
print('Blastoff')
change each time through a loop.
name = input('Enter file:')
handle = open(name, 'r') Sequential
Repeated
counts = dict()
for line in handle: Conditional
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)
name = input('Enter file:') A short Python “Story”
handle = open(name, 'r') about how to count
counts = dict()
words in a file
for line in handle:
words = line.split() A word used to read
for word in words: data from a user
counts[word] = counts.get(word,0) + 1
x = 12.2 x 12.2
y = 14
y 14
Variables
• A variable is a named place in the memory where a programmer can store
data and later retrieve the data using the variable “name”
• Case Sensitive
http://en.wikipedia.org/wiki/Mnemonic
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)
hours = 35.0
What are these bits rate = 12.50
of code doing? pay = hours * rate
print(pay)
Sentences or Lines
x = 2 Assignment statement
x = x + 2 Assignment with expression
print(x) Print statement
x = 3.9 * x * ( 1 - x )
A variable is a memory location x 0.6
used to store a value (0.6)
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4
0.4
The right side is an expression. Once the
expression is evaluated, the result is
placed in (assigned to) the variable on the
0.936
left side (i.e., x).
Expressions…
Numeric Expressions
Operator Operation
• Because of the lack of mathematical
symbols on computer keyboards - we + Addition
use “computer-speak” to express the - Subtraction
classic math operations
* Multiplication
• Asterisk is multiplication / Division
3
Order of Evaluation
• When we string operators together - Python must know which one
to do first
x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
Highest precedence rule to lowest precedence rule:
• Left to right
1 + 2 ** 3 / 4 * 5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11.0 1 + 8 / 4 * 5
>>>
1 + 2 * 5
Parenthesis
Power
Multiplication 1 + 10
Addition
Left to Right 11
Operator Precedence Parenthesis
Power
• Remember the rules top to bottom Multiplication
Addition
• When writing code - use parentheses Left to Right
Conversions
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object
• Why comment?
# All done
print(bigword, bigcount)
Summary
• Type • Integer Division
• Operator precedence
Exercise
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
Acknowledgements / Contributions
No print('Smaller') Program:
Output:
x = 5
Yes if x < 10: Smaller
x > 20 ? print('Smaller') Finis
if x > 20:
No print('Bigger') print('Bigger')
print('Finis')
print('Finis')
Comparison Operators
• Boolean expressions ask a Python Meaning
question and produce a Yes or No < Less than
result which we use to control
program flow <= Less than or Equal to
== Equal to
• Boolean expressions using >= Greater than or Equal to
comparison operators evaluate to
> Greater than
True / False or Yes / No
!= Not equal
• Comparison operators look at
variables but do not change the Remember: “=” is used for assignment.
variables
http://en.wikipedia.org/wiki/George_Boole
Comparison Operators
x = 5
if x == 5 :
print('Equals 5') Equals 5
if x > 4 :
print('Greater than 4') Greater than 4
if x >= 5 :
Greater than or Equals 5
print('Greater than or Equals 5')
if x < 6 : print('Less than 6') Less than 6
if x <= 5 :
print('Less than or Equals 5') Less than or Equals 5
if x != 6 :
print('Not equal 6') Not equal 6
One-Way Decisions
x = 5 Yes
print('Before 5') Before 5 x == 5 ?
if x == 5 :
print('Is 5') Is 5 No print('Is 5’)
print('Is Still 5') Is Still 5
print('Third 5')
print('Afterwards 5')
Third 5 print('Still 5')
print('Before 6') Afterwards 5
if x == 6 : Before 6 print('Third 5')
print('Is 6')
print('Is Still 6')
print('Third 6')
print('Afterwards 6') Afterwards 6
Indentation
• Increase indent indent after an if statement or for statement (after : )
• Maintain indent to indicate the scope of the block (which lines are affected
by the if/for)
• Most text editors can turn tabs into spaces - make sure to enable this
feature
• Python cares a *lot* about how far a line is indented. If you mix tabs and
spaces, you may get “indentation errors” even if everything looks fine
This will save you
much unnecessary
pain.
increase / maintain after if or for
decrease to indicate end of block
x = 5
if x > 2 :
print('Bigger than 2')
print('Still bigger')
print('Done with 2')
for i in range(5) :
print(i)
if i > 2 :
print('Bigger than 2')
print('Done with i', i)
print('All Done')
Think About begin/end Blocks
x = 5
if x > 2 :
print('Bigger than 2')
print('Still bigger')
print('Done with 2')
for i in range(5) :
print(i)
if i > 2 :
print('Bigger than 2')
print('Done with i', i)
print('All Done')
Nested x>1
yes
x = 42
if x > 1 : yes
print('More than one') x < 100
if x < 100 :
no
print('Less than 100') print('Less than 100')
print('All done')
print('All Done')
Two-way Decisions
x=4
• Sometimes we want to
do one thing if a logical no yes
x>2
expression is true and
something else if the
expression is false print('Not bigger') print('Bigger')
if x > 2 :
print('Bigger') print('Not bigger') print('Bigger')
else :
print('Smaller')
print('All done')
print('All Done')
Visualize Blocks x=4
no yes
x = 4 x>2
if x > 2 :
print('Bigger') print('Not bigger') print('Bigger')
else :
print('Smaller')
print('All done')
print('All Done')
More Conditional Structures…
Multi-way
yes
x<2 print('small')
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')
print('All Done')
x=0
Multi-way
yes
x<2 print('small')
x = 0
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')
print('All Done')
x=5
Multi-way
yes
x<2 print('small')
x = 5
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')
print('All Done')
x = 20
Multi-way
yes
x<2 print('small')
x = 20
no
if x < 2 :
yes
print('small')
x < 10 print('Medium')
elif x < 10 :
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')
print('All Done')
Multi-way if x < 2 :
print('Small')
elif x < 10 :
# No Else print('Medium')
x = 5 elif x < 20 :
if x < 2 : print('Big')
print('Small') elif x < 40 :
elif x < 10 : print('Large')
print('Medium') elif x < 100:
print('Huge')
print('All done') else :
print('Ginormous')
Multi-way Puzzles
Which will never print
regardless of the value for x?
if x < 2 :
print('Below 2')
if x < 2 : elif x < 20 :
print('Below 2') print('Below 20')
elif x >= 2 : elif x < 10 :
print('Two or more') print('Below 10')
else : else :
print('Something else') print('Something else')
The try / except Structure
Output Main
Devices Memory
Generic
Software
Computer
Input
Central
Devices
Processing
Unit
Secondary
Memory
Output Main
Devices Memory
astr = 'Hello Bob' When the first conversion fails - it
try: just drops into the except: clause
istr = int(astr) and the program continues.
except:
istr = -1
$ python tryexcept.py
print('First', istr) First -1
Second 123
astr = '123'
try:
istr = int(astr)
except:
istr = -1 When the second conversion
succeeds - it just skips the except:
print('Second', istr) clause and the program continues.
try / except astr = 'Bob'
print('Hello')
astr = 'Bob'
try:
print('Hello') istr = int(astr)
istr = int(astr)
print('There')
except: print('There')
istr = -1
istr = -1
print('Done', istr)
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
Exercise
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
Result
>>> big = max('Hello world')
>>> print(big)
w
>>> tiny = min('Hello world')
>>> print(tiny)
>>>
Max Function
A function is some
>>> big = max('Hello world') stored code that we
>>> print(big) use. A function takes
w
some input and
produces an output.
• This defines the function but does not execute the body of the
function
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
print("I'm a lumberjack, and I'm okay.")
print_lyrics(): print('I sleep all night and I work all day.')
x = 5
print('Hello')
def print_lyrics():
print("I'm a lumberjack, and I'm okay.") Hello
print('I sleep all night and I work all day.')
Yo
print('Yo') 7
x = x + 2
print(x)
Definitions and Uses
• Once we have defined a function, we can call (or invoke) it
as many times as we like
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
print('Yo')
print_lyrics()
x = x + 2
Hello
print(x) Yo
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7
Arguments
• An argument is a value we pass into the function as its input
when we call the function
def greet():
return "Hello" Hello Glenn
Hello Sally
print(greet(), "Glenn")
print(greet(), "Sally")
Return Value
>>> def greet(lang):
... if lang == 'es':
• A “fruitful” function is one ... return 'Hola'
... elif lang == 'fr':
that produces a result (or ... return 'Bonjour'
return value) ... else:
... return 'Hello'
...
• The return statement ends >>> print(greet('en'),'Glenn')
the function execution and Hello Glenn
“sends back” the result of >>> print(greet('es'),'Sally')
Hola Sally
the function >>> print(greet('fr'),'Michael')
Bonjour Michael
>>>
Arguments, Parameters, and
Results
>>> big = max('Hello world') Parameter
>>> print(big)
w
def max(inp):
blah
blah
'Hello world' for x in inp: 'w'
blah
blah
Argument return 'w'
Result
Multiple Parameters / Arguments
• We can define more than one
parameter in the function def addtwo(a, b):
definition added = a + b
return added
• We simply add more arguments
x = addtwo(3, 5)
when we call the function print(x)
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance ...
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.
• It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop
• It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
No Yes
while True: True ?
line = input('> ')
if line == 'done' :
....
break
print(line)
print('Done!')
break
...
http://en.wikipedia.org/wiki/Transporter_(Star_Trek)
print('Done')
Finishing an Iteration with
continue
The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
> hello there
line = input('> ')
if line[0] == '#' : hello there
continue > # don't print this
if line == 'done' : > print this!
break print this!
print(line) > done
print('Done!') Done!
Finishing an Iteration with
continue
The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
> hello there
line = input('> ')
if line[0] == '#' : hello there
continue > # don't print this
if line == 'done' : > print this!
break print this!
print(line) > done
print('Done!') Done!
No
True ? Yes
while True:
line = raw_input('> ') ....
if line[0] == '#' :
continue
if line == 'done' : continue
break
print(line)
...
print('Done!')
print('Done')
Indefinite Loops
• The loops we have seen so far are pretty easy to examine to see
if they will terminate or if they will be “infinite loops”
• We can write a loop to run the loop once for each of the items in
a set using the Python for construct
i=2
3
What is the Largest Number?
41
What is the Largest Number?
12
What is the Largest Number?
9
What is the Largest Number?
74
What is the Largest Number?
15
What is the Largest Number?
What is the Largest Number?
3 41 12 9 74 15
What is the Largest Number?
largest_so_far -1
What is the Largest Number?
largest_so_far 3
What is the Largest Number?
41
largest_so_far 41
What is the Largest Number?
12
largest_so_far 41
What is the Largest Number?
largest_so_far 41
What is the Largest Number?
74
largest_so_far 74
What is the Largest Number?
15
74
What is the Largest Number?
3 41 12 9 74 15
74
Finding the Largest Value
$ python largest.py
largest_so_far = -1 Before -1
print('Before', largest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] :
9 9
if the_num > largest_so_far : 41 41
largest_so_far = the_num 41 12
print(largest_so_far, the_num) 41 3
74 74
print('After', largest_so_far) 74 15
After 74
We make a variable that contains the largest value we have seen so far. If the current
number we are looking at is larger, it is the new largest value we have seen so far.
More Loop Patterns…
Counting in a Loop
$ python countloop.py
zork = 0 Before 0
print('Before', zork) 19
for thing in [9, 41, 12, 3, 74, 15] :
2 41
zork = zork + 1
print(zork, thing) 3 12
print('After', zork) 43
5 74
6 15
After 6
If we just want to search and know if a value was found, we use a variable that
starts at False and is set to True as soon as we find what we are looking for.
How to Find the Smallest Value
$ python largest.py
largest_so_far = -1 Before -1
print('Before', largest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] :
9 9
if the_num > largest_so_far : 41 41
largest_so_far = the_num 41 12
print(largest_so_far, the_num) 41 3
74 74
print('After', largest_so_far) 74 15
After 74
How would we change this to make it find the smallest value in the list?
Finding the Smallest Value
smallest_so_far = -1
print('Before', smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] :
if the_num < smallest_so_far :
smallest_so_far = the_num
print(smallest_so_far, the_num)
print('After', smallest_so_far)
We switched the variable name to smallest_so_far and switched the > to <
Finding the Smallest Value
$ python smallbad.py
smallest_so_far = -1 Before -1
print('Before', smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] :
-1 9
if the_num < smallest_so_far : -1 41
smallest_so_far = the_num -1 12
print(smallest_so_far, the_num) -1 3
-1 74
print('After', smallest_so_far) -1 15
After -1
We switched the variable name to smallest_so_far and switched the > to <
Finding the Smallest Value
smallest = None $ python smallest.py
print('Before') Before
for value in [9, 41, 12, 3, 74, 15] : 99
if smallest is None :
9 41
smallest = value
elif value < smallest :
9 12
smallest = value 33
print(smallest, value) 3 74
print('After', smallest) 3 15
After 3
We still have a variable that is the smallest so far. The first time through the loop
smallest is None, so we take the first value to be the smallest.
The is and is not Operators
• Python has an is operator
smallest = None that can be used in logical
print('Before') expressions
for value in [3, 41, 12, 9, 74, 15] :
if smallest is None :
• Implies “is the same as”
smallest = value
elif value < smallest :
smallest = value • Similar to, but stronger than
print(smallest, value) ==
print('After', smallest)
• is not also is a logical
operator
Summary
• While loops (indefinite) • For loops (definite)
• Infinite loops • Iteration variables
• Using break • Loop idioms
• Using continue • Largest or smallest
• None constants and variables
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance ...
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.
• So be careful when
1, in <module>
IndexError: string index out
constructing index values of range
and slices >>>
Strings Have Length
b a n a n a
The built-in function len gives 0 1 2 3 4 5
us the length of a string
>>> fruit = 'banana'
>>> print(len(fruit))
6
len Function
>>> fruit = 'banana' A function is some stored
>>> x = len(fruit) code that we use. A
>>> print(x) function takes some
6 input and produces an
output.
'banana' len() 6
(a number)
(a string) function
len Function
>>> fruit = 'banana' A function is some stored
>>> x = len(fruit) code that we use. A
>>> print(x) function takes some
6 input and produces an
output.
def len(inp):
blah
'banana' blah 6
(a string) for x in y:
blah
(a number)
blah
Looping Through Strings
print(letter)
The iteration variable “iterates” through the string and the block (body)
of code is executed once for each value in the sequence
More String Operations
Slicing Strings M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
• We can also look at any
continuous section of a string
using a colon operator >>> s = 'Monty Python'
>>> print(s[0:4])
• The second number is one Mont
beyond the end of the slice - >>> print(s[6:7])
“up to but not including” P
>>> print(s[6:20])
• If the second number is
Python
beyond the end of the string,
it stops at the end
Slicing Strings M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
https://docs.python.org/3/library/stdtypes.html#string-methods
String Library
str.capitalize() str.replace(old, new[, count])
str.center(width[, fillchar]) str.lower()
str.endswith(suffix[, start[, end]]) str.rstrip([chars])
str.find(sub[, start[, end]]) str.strip([chars])
str.lstrip([chars]) str.upper()
Searching a String
b a n a n a
• We use the find() function to search
for a substring within another string
0 1 2 3 4 5
Secondary
if x < 3: print Memory
Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772
http://www.py4e.com/code/mbox-short.txt
Opening a File
• Before we can read the contents of the file, we must tell Python
which file we are going to work with and what we will be doing
with the file
• filename is a string
Details: http://source.sakaiproject.org/viewsvn/?view=rev&rev=39772
File Processing
A text file has newlines at the end of each line
• Remember - a sequence is an
ordered set
Counting Lines in a File
fhand = open('mbox.txt')
• Open a file read-only count = 0
for line in fhand:
• Use a for loop to read each line count = count + 1
print('Line Count:', count)
• Count the lines and print out
the number of lines
$ python open.py
Line Count: 132045
Reading the *Whole* File
>>> fhand = open('mbox-short.txt')
We can read the whole >>> inp = fhand.read()
file (newlines and all) >>> print(len(inp))
94626
into a single string
>>> print(inp[:20])
From stephen.marquar
Searching Through a File
From: [email protected]
From: [email protected]
...
OOPS!
What are all these blank From: [email protected]\n
lines doing here? \n
From: [email protected]\n
• Each line from the file \n
has a newline at the end From: [email protected]\n
\n
• The print statement adds From: [email protected]\n
a newline to each line \n
...
Searching Through a File (fixed)
fhand = open('mbox-short.txt')
• We can strip the whitespace for line in fhand:
from the right-hand side of line = line.rstrip()
if line.startswith('From:') :
the string using rstrip() from print(line)
the string library
From: [email protected]
• The newline is considered
From: [email protected]
“white space” and is From: [email protected]
stripped From: [email protected]
....
Skipping with continue
fhand = open('mbox-short.txt')
We can conveniently for line in fhand:
skip a line by using the line = line.rstrip()
if not line.startswith('From:') :
continue statement continue
print(line)
Using in to Select Lines
fhand = open('mbox-short.txt')
We can look for a string for line in fhand:
anywhere in a line as our line = line.rstrip()
if not '@uct.ac.za' in line :
selection criteria continue
print(line)
Bad File
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
Names quit()
count = 0
for line in fhand:
if line.startswith('Subject:') :
count = count + 1
print('There were', count, 'subject lines in', fname)
• Data Structure
- A particular way of organizing data in a computer
https://en.wikipedia.org/wiki/Algorithm
https://en.wikipedia.org/wiki/Data_structure
What is Not a “Collection”?
Most of our variables have one value in them - when we put a new
value in the variable, the old value is overwritten
$ python
>>> x = 2
>>> x = 4
>>> print(x)
4
A List is a Kind of
Collection
• A collection allows us to put many values in a single “variable”
Just like strings, we can get at any single element in a list using an
index specified in square brackets
http://docs.python.org/tutorial/datastructures.html
Building a List from Scratch
>>> stuff = list()
• We can create an empty list >>> stuff.append('book')
and then add elements using >>> stuff.append(99)
the append method >>> print(stuff)
['book', 99]
• The list stays in order and >>> stuff.append('cookie')
>>> print(stuff)
new elements are added at
['book', 99, 'cookie']
the end of the list
Is Something in a List?
• Python provides two operators >>> some = [1, 9, 21, 10, 16]
that let you check if an item is >>> 9 in some
True
in a list
>>> 15 in some
False
• These are logical operators >>> 20 not in some
that return True or False True
>>>
• They do not modify the list
Lists are in Order
• A list can hold many
items and keeps
those items in the
order until we do >>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
>>> friends.sort()
something to change >>> print(friends)
the order ['Glenn', 'Joseph', 'Sally']
>>> print(friends[1])
• A list can be sorted Joseph
(i.e., change its order) >>>
Split breaks a string into parts and produces a list of strings. We think of these
as words. We can access a particular word or loop through all the words.
>>> line = 'A lot of spaces'
>>> etc = line.split()
>>> print(etc)
['A', 'lot', 'of', 'spaces'] ● When you do not specify a
>>>
>>> line = 'first;second;third' delimiter, multiple spaces are
>>> thing = line.split()
>>> print(thing) treated like one delimiter
['first;second;third']
>>> print(len(thing))
1 ● You can specify what delimiter
>>> thing = line.split(';')
>>> print(thing) character to use in the splitting
['first', 'second', 'third']
>>> print(len(thing))
3
>>>
From [email protected] Sat Jan 5 09:14:16 2008
words = line.split()
email = words[1]
print pieces[1]
The Double Split Pattern
words = line.split()
email = words[1] [email protected]
print pieces[1]
The Double Split Pattern
words = line.split()
email = words[1] [email protected]
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print pieces[1]
The Double Split Pattern
words = line.split()
email = words[1] [email protected]
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print(pieces[1]) 'uct.ac.za'
List Summary
• Concept of a collection • Slicing lists
$ python
>>> x = 2
>>> x = 4
>>> print(x)
4
A Story of Two Collections..
• List
• Dictionary
perfume
money
candy
http://en.wikipedia.org/wiki/Associative_array
Dictionaries
• Dictionaries are Python’s most powerful data collection
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
if name not in counts: {'csev': 2, 'zqian': 1, 'cwen': 2}
counts[name] = 1
else :
counts[name] = counts[name] + 1
print(counts)
The get Method for Dictionaries
The pattern of checking to see if a if name in counts:
key is already in a dictionary and x = counts[name]
assuming a default value if the key else :
is not there is so common that there x = 0
is a method called get() that does
this for us
x = counts.get(name, 0)
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
counts[name] = counts.get(name, 0) + 1
print(counts)
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
counts[name] = counts.get(name, 0) + 1
print(counts)
http://www.youtube.com/watch?v=EHJ9uYx5L58
Counting Words in Text
Writing programs (or programming) is a very creative and rewarding activity. You can write
programs for many reasons ranging from making your living to solving a difficult data analysis
problem to having fun to helping someone else solve a problem. This book assumes that
everyone needs to know how to program and that once you know how to program, you will figure
out what you want to do with your newfound skills.
We are surrounded in our daily lives with computers ranging from laptops to cell phones. We
can think of these computers as our “personal assistants” who can take care of many things on
our behalf. The hardware in our current-day computers is essentially built to continuously ask us
the question, “What would you like me to do next?”
Our computers are fast and have vast amounts of memory and could be very helpful to us if we
only knew the language to speak to explain to the computer what we would like it to do next. If
we knew this language we could tell the computer to do tasks on our behalf that were repetitive.
Interestingly, the kinds of things computers can do best are often the kinds of things that we
humans find boring and mind-numbing.
Counting Pattern
counts = dict()
print('Enter a line of text:')
The general pattern to count the
line = input('')
words in a line of text is to split
words = line.split() the line into words, then loop
through the words and use a
print('Words:', words) dictionary to track the count of
print('Counting...')
each word independently.
for word in words:
counts[word] = counts.get(word,0) + 1
print('Counts', counts)
python wordcount.py
Enter a line of text:
the clown ran after the car and the car ran into the tent
and the tent fell down on the clown and the car
http://www.flickr.com/photos/71502646@N00/2526007974/
python wordcount.py
counts = dict() Enter a line of text:
line = input('Enter a line of text:') the clown ran after the car and the car ran
words = line.split()
into the tent and the tent fell down on the
print('Words:', words) clown and the car
print('Counting...’)
Words: ['the', 'clown', 'ran', 'after', 'the', 'car',
for word in words: 'and', 'the', 'car', 'ran', 'into', 'the', 'tent', 'and',
counts[word] = counts.get(word,0) + 1 'the', 'tent', 'fell', 'down', 'on', 'the', 'clown',
print('Counts', counts)
'and', 'the', 'car']
Counting...
bigcount = None
bigword = None
python words.py
for word,count in counts.items(): Enter file: clown.txt
if bigcount is None or count > bigcount: the 7
bigword = word
bigcount = count
print(bigword, bigcount)
Using two nested loops
Summary
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
...
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.
>>> t = tuple()
>>> dir(t)
['count', 'index']
Tuples are More Efficient
• Since Python does not have to build tuple structures to be
modifiable, they are simpler and more efficient in terms of
memory use and performance than lists
• So in our program when we are making “temporary variables”
we prefer tuples over lists
Tuples and Assignment
• We can also put a tuple on the left-hand side of an assignment
statement
• We can even omit the parentheses
lst = []
for key, val in counts.items():
newtup = (val, key)
lst.append(newtup)
Object
String
Objects get
created and
used Output
Input
Code/Data
Code/Data
Code/Data
Code/Data
Objects are
bits of code
and data Output
Input
Code/Data
Code/Data
Code/Data
Code/Data
Objects hide detail
- they allow us to
ignore the detail of
the “rest of the Output
program”.
Input
Code/Data
Code/Data
Code/Data
Code/Data
Objects hide detail -
they allow the “rest
of the program” to
ignore the detail Output
about “us”.
Definitions
• Class - a template
• Method or Message - A defined capability of a class
• Field or attribute- A bit of data in a class
• Object or Instance - A particular instance of a class
Terminology: Class
Defines the abstract characteristics of a thing (object), including the
thing's characteristics (its attributes, fields or properties) and the
thing's behaviors (the things it can do, or methods, operations or
features). One might say that a class is a blueprint or factory that
describes the nature of something. For example, the class Dog would
consist of traits shared by all dogs, such as breed and fur color
(characteristics), and the ability to bark and sit (behaviors).
http://en.wikipedia.org/wiki/Object-oriented_programming
Terminology: Instance
One can have an instance of a class or a particular object.
The instance is the actual object created at runtime. In
programmer jargon, the Lassie object is an instance of the
Dog class. The set of values of the attributes of a particular
object is called its state. The object consists of state and the
behavior that's defined in the object's class.
Object and Instance are often used interchangeably.
http://en.wikipedia.org/wiki/Object-oriented_programming
Terminology: Method
An object's abilities. In language, methods are verbs. Lassie, being a
Dog, has the ability to bark. So bark() is one of Lassie's methods. She
may have other methods as well, for example sit() or eat() or walk() or
save_timmy(). Within the program, using a method usually affects
only one particular object; all Dogs can bark, but you need only one
particular dog to do the barking
http://en.wikipedia.org/wiki/Object-oriented_programming
Some Python Objects
>>> dir(x)
>>> x = 'abc' [ … 'capitalize', 'casefold', 'center', 'count',
>>> type(x) 'encode', 'endswith', 'expandtabs', 'find',
<class 'str'> 'format', … 'lower', 'lstrip', 'maketrans',
>>> type(2.5) 'partition', 'replace', 'rfind', 'rindex', 'rjust',
<class 'float'> 'rpartition', 'rsplit', 'rstrip', 'split',
>>> type(2) 'splitlines', 'startswith', 'strip', 'swapcase',
<class 'int'> 'title', 'translate', 'upper', 'zfill']
>>> y = list() >>> dir(y)
>>> type(y) [… 'append', 'clear', 'copy', 'count', 'extend',
<class 'list'> 'index', 'insert', 'pop', 'remove', 'reverse',
>>> z = dict() 'sort']
>>> type(z) >>> dir(z)
<class 'dict'> […, 'clear', 'copy', 'fromkeys', 'get', 'items',
'keys', 'pop', 'popitem', 'setdefault', 'update',
'values']
A Sample Class
This is the template
class is a reserved
class PartyAnimal: for making
word
x=0 PartyAnimal objects
def party(self) :
self.x = self.x + 1
print("So far",self.x)
an = PartyAnimal()
an.party()
an.party()
an.party()
class PartyAnimal:
$ python party1.py
x=0
def party(self) :
self.x = self.x + 1
print("So far",self.x)
an
an = PartyAnimal()
x 0
party()
an.party()
an.party()
an.party()
class PartyAnimal: $ python party1.py
x=0 So far 1
So far 2
def party(self) : So far 3
self.x = self.x + 1
print("So far",self.x)
an
self x
an = PartyAnimal()
party()
an.party()
an.party()
an.party() PartyAnimal.party(an)
Playing with dir() and type()
A Nerdy Way to Find Capabilities
>>> y = list()
• The dir() command lists >>> type(y)
capabilities <class 'list'>
>>> dir(y)
• Ignore the ones with underscores ['__add__', '__class__',
- these are used by Python itself '__contains__', '__delattr__',
'__delitem__', '__delslice__',
'__doc__', … '__setitem__',
• The rest are real operations that '__setslice__', '__str__',
the object can perform 'append', 'clear', 'copy',
'count', 'extend', 'index',
• It is like type() - it tells us 'insert', 'pop', 'remove',
'reverse', 'sort']
something *about* a variable >>>
class PartyAnimal:
x = 0
We can use dir() to find
the “capabilities” of our
def party(self) : newly created class.
self.x = self.x + 1
print("So far",self.x)
an = PartyAnimal()
$ python party3.py
print("Type", type(an)) Type <class '__main__.PartyAnimal'>
print("Dir ", dir(an)) Dir ['__class__', ... 'party', 'x']
Try dir() with a String
>>> x = 'Hello there'
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__',
'__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__getslice__', '__gt__',
'__hash__', '__init__', '__le__', '__len__', '__lt__',
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__',
'capitalize', 'center', 'count', 'decode', 'encode', 'endswith',
'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit',
'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex',
'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
Object Lifecycle
http://en.wikipedia.org/wiki/Constructor_(computer_science)
Object Lifecycle
• Objects are created, used, and discarded
• We have special blocks of code (methods) that get called
- At the moment of creation (constructor)
- At the moment of destruction (destructor)
• Constructors are used a lot
• Destructors are seldom used
Constructor
The primary purpose of the constructor is to set up some
instance variables to have the proper initial values when
the object is created
class PartyAnimal:
x = 0
$ python party4.py
def __init__(self):
I am constructed
print('I am constructed')
So far 1
def party(self) : So far 2
self.x = self.x + 1 I am destructed 2
print('So far',self.x) an contains 42
def __del__(self):
print('I am destructed', self.x)
http://en.wikipedia.org/wiki/Constructor_(computer_science)
Many Instances
• We can create lots of objects - the class is the template
for the object
• We can store each distinct object in its own variable
s = PartyAnimal("Sally")
j = PartyAnimal("Jim")
s.party()
j.party()
s.party() party5.py
class PartyAnimal:
x = 0
name = ""
def __init__(self, z):
self.name = z
print(self.name,"constructed")
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
s = PartyAnimal("Sally")
j = PartyAnimal("Jim")
s.party()
j.party()
s.party()
class PartyAnimal:
x = 0
name = "" s
def __init__(self, z): x: 0
self.name = z
print(self.name,"constructed")
name:
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
s = PartyAnimal("Sally")
j = PartyAnimal("Jim")
s.party()
j.party()
s.party()
class PartyAnimal:
x = 0
name = "" s
def __init__(self, z): x: 0
self.name = z
print(self.name,"constructed")
name: Sally
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
s = PartyAnimal("Sally") j
j = PartyAnimal("Jim") x: 0
We have two
s.party()
j.party()
independent name: Jim
s.party() instances
class PartyAnimal:
x = 0
name = "" Sally constructed
def __init__(self, z): Jim constructed
self.name = z Sally party count 1
Jim party count 1
print(self.name,"constructed")
Sally party count 2
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
s = PartyAnimal("Sally")
j = PartyAnimal("Jim")
s.party()
j.party()
s.party()
Inheritance
http://www.ibiblio.org/g2swap/byteofpython/read/inheritance.html
Inheritance
• When we make a new class - we can reuse an existing
class and inherit all the capabilities of an existing class
and then add our own little bit to make our new class
• Another form of store and reuse
• Write once - reuse many times
• The new class (child) has all the capabilities of the old
class (parent) - and then some more
Terminology: Inheritance
http://en.wikipedia.org/wiki/Object-oriented_programming
class PartyAnimal:
x = 0 s = PartyAnimal("Sally")
name = "" s.party()
def __init__(self, nam):
self.name = nam j = FootballFan("Jim")
print(self.name,"constructed") j.party()
j.touchdown()
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
FootballFan is a class which
class FootballFan(PartyAnimal):
extends PartyAnimal. It has all
points = 0
def touchdown(self): the capabilities of PartyAnimal
self.points = self.points + 7 and more.
self.party()
print(self.name,"points",self.points)
class PartyAnimal:
x = 0 s = PartyAnimal("Sally")
name = "" s.party()
def __init__(self, nam):
self.name = nam j = FootballFan("Jim")
print(self.name,"constructed") j.party()
j.touchdown()
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x) s
x:
class FootballFan(PartyAnimal):
points = 0
def touchdown(self):
name: Sally
self.points = self.points + 7
self.party()
print(self.name,"points",self.points)
class PartyAnimal:
x = 0 s = PartyAnimal("Sally")
name = "" s.party()
def __init__(self, nam):
self.name = nam j = FootballFan("Jim")
print(self.name,"constructed") j.party()
j.touchdown()
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x) j
x:
class FootballFan(PartyAnimal):
points = 0
def touchdown(self): name: Jim
self.points = self.points + 7
self.party() points:
print(self.name,"points",self.points)
Definitions
• Class - a template
• Attribute – A variable within a class
• Method - A function within a class
• Object - A particular instance of a class
• Constructor – Code that runs when an object is created
• Inheritance - The ability to extend a class to make a new class.
Summary
• Object Oriented programming is a very structured
approach to code reuse
• Photo from the television program Lassie. Lassie watches as Jeff (Tommy Rettig) works on his bike is Public
Domain
https://en.wikipedia.org/wiki/Lassie#/media/File:Lassie_and_Tommy_Rettig_1956.JPG