Python Mod2
Python Mod2
Iteration
Strings
Files
1
UPDATING VARIABLES
A common pattern in assignment statements is an assignment statement
that updates a variable - where the new value of the variable depends on
the old.
This means “get the current value of x , add one, and then update x with
the new value.”
If you try to update a variable that doesn’t exist, you get an error, because
Python evaluates the right side before it assigns a value to x :
Before you can update a variable, you have to initialize it, usually with a
simple assignment:
3
THE WHILE STATEMENT
n=5
No Yes
n>0? Program: Output:
7
“INFINITE LOOPS” AND BREAK
Sometimes you don’t know it’s time to end a loop until
you get half way through the body.
In that case you can write an infinite loop on purpose and
then use the break statement to jump out of the loop.
This loop is obviously an infinite loop because the
logical expression on the while statement is simply the
logical constant True :
8
INFINITE LOOP
If you make the mistake and run this code, you will learn
quickly that this program will run forever or until your
battery runs out
Because the logical expression at the top of the loop is
always true by virtue of the fact that the expression is the
constant value True
9
n=5
print(‘Lather‘) n=5
while n > 0 :
print(‘Rinse‘) print (‘Lather’)
print (‘Rinse‘)
print(‘Dry off!’)
print(‘Dry off!‘)
print(‘Lather‘) n=0
while n > 0 :
print(‘Rinse‘) print(‘Lather’)
print(‘Rinse‘)
print(‘Dry off!‘)
print(‘Dry off!‘)
What does this loop do?
BREAKING OUT OF A LOOP
While this is a dysfunctional infinite loop, we can still
use this pattern to build useful loops as long as we
carefully add code to the body of the loop to explicitly
exit the loop using break when we have reached the exit
condition.
For example, suppose you want to take input from the
user until they type done .
You could write:
1
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!
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!
BREAKING OUT OF A LOOP
The loop condition is True , which is always true, so the
loop runs repeatedly until it hits the break statement.
Each time through, it prompts the user with an angle
bracket.
If the user types done , the break statement exits the
loop.
Otherwise the program echoes whatever the user types
and goes back to the top of the loop.
1
FINISHING AN ITERATION WITH
CONTINUE
Sometimes you are in an iteration of a loop and want to
finish the current iteration and immediately jump to the
next iteration.
In that case you can use the continue statement to skip to
the next iteration without finishing the body of the loop
for the current iteration.
Here is an example of a loop that copies its input until
the user types “done”, but treats lines that start with the
hash character as lines not to be printed (kind of like
Python comments).
1
FINISHING AN ITERATION WITH
CONTINUE
while True:
> hello there
line = input('> ')
hello there
if line[0] == '#' :
> # don't print this
continue
> print this!
if line == 'done':
print this!
break
> done
print(line)
Done!
print('Done!‘)
FINISHING AN ITERATION WITH
CONTINUE
while True:
> hello there
line = input('> ')
hello there
if line[0] == '#' :
> # don't print this
continue
> print this!
if line == 'done' :
print this!
break
> done
print(line)
Done!
print('Done!‘)
FINISHING AN ITERATION WITH
CONTINUE
All the lines are printed except the one that starts with
the hash sign because when the continue is executed, it
ends the current iteration and jumps back to the while
statement to start the next iteration, thus skipping the
print statement.
1
INDEFINITE LOOPS
While loops are called "indefinite loops" because they
keep going until a logical condition becomes False
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"
Sometimes it is a little harder to be sure if a loop will
terminate
DEFINITE LOOPS
Sometimes we want to loop through a set of things such
as a list of words, the lines in a file or a list of numbers.
When we have a list of things to loop through, we can
construct a definite loop using a for statement.
We call the while statement an indefinite loop because
it simply loops until some condition becomes False
The for loop is looping through a known set of items so
it runs through as many iterations as there are items in
the set.
We say that "definite loops iterate through the members
of a set"
A DEFINITE LOOP WITH STRINGS
5
4
for i in [5, 4, 3, 2, 1] :
3
print(i)
2
print(‘Blastoff!‘’)
1
Blastoff!
A SIMPLE DEFINITE LOOP
No
Yes
Done? Move i ahead 5
4
for i in [5, 4, 3, 2, 1] :
3
print(i) print(i)
2
print('Blastoff!‘)
1
Blastoff!
print(‘Blast off!‘)
Definite loops (for loops) have explicit iteration
variables that change each time through a loop. These
iteration variables move through the sequence or set.
LOOKING AT IN...
We set the variable count to zero before the loop starts, then we
write a for loop to run through the list of numbers.
Our iteration variable is named itervar and while we do not use
itervar in the loop, it does control the loop and cause the loop
body to be executed once for each of the values in the list.
In the body of the loop, we add one to the current value of count
for each of the values in the list
2
SUMMING LOOPS
$ python basicloop.py
Before
9
print(‘Before’)
41
for thing in [9, 41, 12, 3, 74, 15] :
12
print(thing)
3
print(‘After’)
74
15
After
COUNTING IN A LOOP
$ python countloop.py
zork = 0 Before 0
print('Before', zork) 99
for thing in [9, 41, 12, 3, 74, 15] : 50 41
zork = zork + thing 62 12
print(zork, thing) 65 3
print('After', zork) 139 74
154 15
After 154
count = 0
sum = 0 $ python averageloop.py
print('Before', count, sum) Before 0 0
for value in [9, 41, 12, 3, 74, 15] : 199
count = count + 1 2 50 41
sum = sum + value 3 62 12
print(count, sum, value) 4 65 3
print('After', count, sum, sum / count) 5 139 74
6 154 15
After 6 154 25.666
An average just combines the counting and sum patterns and divides when the
loop is done.
FILTERING IN A LOOP
print(‘Before’) $ python search1.py
for value in [9, 41, 12, 3, 74, 15] : Before
if value > 20: Large number 41
print('Large number', value) Large number 74
print(‘After’) After
If we just want to search and know if a value was found - we use a variable that start
at False and is set to True as soon as we find what we are looking for.
FIND THE LARGEST NUMBER
3
SUMMARY
While loops (indefinite)
Infinite loops
Using break
Using continue
Iteration variables
Largest or smallest
STRING DATA TYPE
A string is a sequence of >>> str1 = "Hello”
characters >>> str2 = 'there'
A string literal uses quotes
>>> bob = str1 + str2
>>> print(bob)
'Hello' or “Hello” Hellothere
For strings, + means >>> str3 = '123'
“concatenate” >>> str3 = str3 + 1
When a string contains Traceback (most recent call last):
numbers, it is still a string File "<stdin>", line 1, in
<module>TypeError: cannot
We can convert numbers in a
concatenate 'str' and 'int' objects
string into a number using int() >>> x = int(str3) + 1
>>> print(x)
124
>>>
READING
AND >>> name = input('Enter:')
Enter:Chuck
CONVERTING >>> print(name)
Chuck
• We prefer to read data in >>> apple = input('Enter:')
using strings and then Enter:100
parse and convert the data >>> x = apple – 10
as we need Traceback (most recent call last): File
• This gives us more control "<stdin>", line 1, in
over error situations <module>TypeError: unsupported
and/or bad user input operand type(s) for -: 'str' and 'int'
• Raw input numbers must >>> x = int(apple) – 10
be converted from strings >>> print(x)
90
LOOKING INSIDE STRINGS
a
4
STRING LENGTH
Alternatively, you can use negative indices, which count
backward from the end of the string.
The expression fruit[-1] yields the last letter, fruit[-2]
yields the second to last, and so on.
4
LOOPING THROUGH STRINGS
M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
The “object” in this case is the string and the “item” is the character you
tried to assign.
The reason for the error is that strings are immutable, which means you
can’t change an existing string.
The best you can do is create a new string that is a variation on the original:
This example concatenates a new first letter onto a slice of greeting . It has
no effect on the original string.
5
USING IN AS AN OPERATOR
Python does not handle uppercase and lowercase letters the same way that people do.
All the uppercase letters come before all the lowercase letters, so:
A common way to address this problem is to convert strings to a standard format, such as
all lowercase, before performing the comparison.
5
STRING LIBRARY
• Python has a number of string functions
which are in the string library
• These functions are already built into every
string - we invoke them by appending the
function to the string variable
>>> greet = 'Hello Bob‘
• These functions do not modify the original
string, instead they return a new string that
>>> zap = greet.lower()
has been altered string methods >>> print(zap)
• Strings are an example of Python objects. hello bob
• An object contains both data (the actual >>> print(greet)
string itself) as well as methods Hello Bob
• Methods are effectively functions which >>> print(‘Hi There'.lower()’)
that are built into the object and are hi there
available to any instance of the object. >>>
Python has a function called
dir() that lists the methods
>>> stuff = 'Hello world’ available for an object.
>>> type(stuff)
<class ‘str’>
>>> dir(stuff)
['capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
'find', 'format', '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']
http://docs.python.org/lib/string-methods.html
CALLING A STRING OBJECT METHOD
Calling a method is similar to calling a function—it
takes arguments and returns a value—but the syntax is
different.
We call a method by appending the method name to the
variable name using the period as a delimiter.
6
STRING LIBRARY
http://docs.python.org/lib/string-methods.html
SEARCHING A STRING
The replace()
function is like a >>> greet = 'Hello Bob'
“search and replace” >>> nstr = greet.replace('Bob','Jane')
operation in a word >>> print(nstr)
processor Hello Jane
It replaces all >>> nstr = greet.replace('o','X')
occurrences of the >>> print(nstr)
search string with the HellX BXb
replacement string >>>
STRIPPING WHITESPACE
• Sometimes we want to
take a string and remove >>> greet = ' Hello Bob '
whitespace at the >>> greet.lstrip()
beginning and/or end 'Hello Bob '
>>> greet.rstrip()
• lstrip() and rstrip() to the 'Hello Bob'
left and right only >>> greet.strip()
• strip() Removes both begin 'Hello Bob'
and ending whitespace >>>
PREFIXES
Some methods such as startswith return boolean values.
You will note that startswith requires case to match so sometimes we take a line and map it all
to lowercase before we do any checking using the lower method.
In the last example, the method lower is called and then we use startswith to check to see if
the resulting lowercase string starts with the letter “p”.
As long as we are careful with the order, we can make multiple method calls in a single
expression.
6
Parsing and Extracting
21 31
6
FORMAT OPERATOR
For example, the format sequence ' %d ' means that the
second operand should be formatted as an integer ( d
stands for “decimal”):
6
FORMAT OPERATOR
The following example uses '%d' to format an integer, '%g'
to format a floating point number, and '%s' to format a
string:
Secondary
if x< 3: print Memory
http://www.py4inf.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
This is done with the open() function
http://docs.python.org/lib/built-in-funcs.html
WHAT IS A HANDLE?
$ python open.py
Line Count: 132045
SEARCHING THROUGH A FILE
• We can put an if statement in our for loop to only print lines
that meet some criteria
fhand = open('mbox-short.txt')
for line in fhand:
if line.startswith('From:') :
print(line)
OOPS!
From: [email protected]
From: [email protected]
...
OOPS!
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From:') :
continue
print(line)
USING IN TO SELECT LINES
•We can look for a string anywhere in a line as our selection
criteria
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not '@uct.ac.za' in line :
continue
print(line)
The write method of the file handle object puts data into the file.
When you are done writing, you have to close the file to make
sure that the last bit of data is physically written to the disk so it
will not be lost if the power goes off.
9
SUMMARY
• Secondary storage
• Opening a file - file handle
• File structure - newline character
• Reading a file line-by-line with a for loop
• Searching for lines
• Reading file names
• Dealing with bad files