Control Structures in Python

Preview:

DESCRIPTION

Control Structures in Python. So Far …. We can step through the items in a list, a tuple , a string, or a range [ start:stop:step ] However, we cannot yet perform operations (or not) based on some condition include multiple instructions for each item in the sequence. - PowerPoint PPT Presentation

Citation preview

Control Structures in Python

2

So Far …• We can step through the items in a list, a

tuple, a string, or a range– [start:stop:step]

• However, we cannot yet– perform operations (or not) based on some

condition– include multiple instructions for each item in

the sequence.• Control structures in a language allow these

3

First, Extending I/O options• File object can be created with open() built-in function.

– open(filename, mode) – mode = “r”, “w”, ”a”, ”r+” mode = “r” assumed if not

specified. (read, write, append, read/write)• File methods: (Selected)

– file.close()– file.flush()– file.read([size]) -- read at most size bytes from the file. If size

omitted, read to end of file– file.readline([size]) – read one line of the file. Optional size

determines maximum number of bytes returned and may produce an incomplete line.

– file.readlines() – read to EOF, returning a list of the file lines– file.write(str) – write str to file. May need flush or close to

complete the file write– writelines(sequence) – writes a sequence, usually a list of strings

4

IF …• Simplest control

– Do some specified instructions if a given condition is true

if <condition>: <instruction(s) to execute>

– Extension: Do specified instructions if a condition is true, otherwise do something else.

if <condition>: <instruction(s) to execute if true>else: <instruction(s) to execute if false>

Note: indentation and punctuation are required.

5

Examples of IF

seq=raw_input("Enter a DNA sequence: ")pattern=raw_input("Enter the pattern: ")if len(pattern)>len(seq): print "Error: Pattern length exceeds string length"else: print "sequence and pattern: ", seq, " ", pattern

Python’s requirement of indentation to delimit blocks of code – not popular, but not a serious issue after getting used to it.The : at the end of the if clause and the else clause may seem awkward, but they are required parts of the python syntax.

6

The Flow Chart

Condition test

Block to execute when condition fails

Block to execute when condition true

False True

7

Nested IF

• Sometimes, the block to be executed in one branch (or both branches) contain other if statements or other control structures.

8

Condition test

Block to execute when condition true

False True

Each block may contain any combination of instructions, function calls, etc.

9

Nested if exampleConsider this example code:

values = range(27,150,4)print valuesx=raw_input("Enter x:")if x in values: print "x in value set", xelse: if x> 50: print "new x greater than 50" else: print "new x less than 50"

Understand what it is supposed to do?

Predict the output, x = 43Run it

Explain what is wrong

10

if .. else .. if

• The combination if .. else .. if occurs frequently enough that python (and some other languages) offers a shortcut.

• elif combines the else and if – elif x>50

11

values = range(27,150,4)print valuesstrx=raw_input("Enter x:")x=int(strx)# or x=int(raw_input("Enter x: "))if x in values: print "x in value set", xelif x> 50: print "new x greater than 50"else: print "new x less than 50"

12

Short spot check

• Usual drill – pairs of students• Left side (as I see you) do Practice 4.20

and 4.24• Right side, do Practice 4.22 and 4.23

• Presenters different from last week.• Look at the other questions so you can ask

questions and be sure to understand both sets. 10 to 15 minutes should do it

13

Repetition

• Now we can decide which path to take, let’s add the ability to repeat a block of statements without having to put them in the code several times.

• for loops• while loops• function calls• Loops may be nested, may contain

conditionals in the block, may contain any other legitimate code in the block.

14

for …

• Sometimes called an iterative loop.• A loop variable takes on each value in a

specified sequence, executes the body of the code with the current value, repeats for each value.

for <variable> in <sequence>:<block of code to execute>

• Sequence may be a list, a range, a tuple, a string

15

Flowchart for for loop

Set iteration variable to initial or next value

variable in range? Loop bodyTrue

False

Skip loop body if initial iteration variable value is out of range.

16

Input from a file• Built-in file class– Two ways to input a line from the file:• line=source.readline()• for line in source:

filename=raw_input('File to read: ')source = file(filename) #Access is read-onlyfor line in source: print line

where line and source are local names, source previously defined

Note – no explicit read in the for loop

17

Iterating through a string

teststring = "When in the course of human events, \

it becomes necessary ..."countc = 0for c in teststring: if c == "a": countc +=1print "Number of c's in the string: ", countc

18

Stepping through a list

cousins=["Mike", "Carol", "Frank", "Ann", "Jim", \"Pat", "Franny”,"Elizabeth", "Richard", "Sue"]steps = range(len(cousins))for step in steps: print cousins[step]+", ",

Output: Mike, Carol, Frank, Ann, Jim, Pat, Franny, Elizabeth, Richard, Sue,

Spot check Exercise: Exactly what is steps (type and content)? Get rid of that last comma.

19

Stepping through the list again

• OutputMike, Carol, Frank, Ann, Jim, Pat, Franny, Elizabeth, Richard,

Sue,

cousins=["Mike", "Carol", "Frank", "Ann", "Jim", \"Pat", "Franny”,"Elizabeth", "Richard", "Sue"]for step in range(len(cousins)): print cousins[step]+", ”,

20

Stepping through a file# Based on Figure 8.4 of Object Oriented Programming in # Pythonfilename=raw_input("Enter filename: ")source=file(filename)numlines = numwords = numchars = 0for line in source: numlines += 1 numwords += len(line.split()) numchars +=len(line) print lineprint "The file contains ", numlines, " lines, ", numwords, " words, and ", numchars, "characters."source.close()

21

Danger – modifying iteration variable

original = ["A","B","C","D","E","F"]for entry in original: print "Current entry: ", entry original.remove(entry) print "List with ", entry, " removed. ", original

original.append(entry) print "List with ", entry, " appended. ", originalprint "List at end of loop:\n ", original

Predict the output

22

While loops• for loops are iterated over the elements of

a sequence. You can know exactly how many times the loop will execute by checking the length of the sequence.

• while allows more flexible loop control– repeat the loop as long as a specified condition

is true– danger of loop not terminating– stop when a goal is reached without going

through more steps than needed.

23

Silly example

ans=raw_input('Shall we play a game? ')while answer.lower() in ('y', 'yes'): #code for playing game ans= raw_input('Would you like to play again? ')

24

Operation of the while

Condition Loop bodyTrue

False

Note – condition is tested before the loop body is ever executed. It is possible that the loop body will not be executed at all.

25

Spot check• Exercise 5.8 (Write a program that answers

the following question. Starting with x = 1, how many times can x be doubled before reaching one million or more?

• Exercise 5.10: Write a prgram that allows the user to end=ter words, continuing until the user enters a duplicate. When a duplicate is encountered, print “You already entered” then the duplicated word. Then “You entered n distinct words” where n is the correct number.

26

Read while data remains# Based on Figure 8.3 of Object Oriented Programming in #Pythonfilename=raw_input("Enter filename: ")source=file(filename)numlines = numwords = numchars = 0line = source.readline()while line: numlines += 1 numwords += len(line.split()) numchars +=len(line) line = source.readline()print "The file contains ", numlines, " lines, ", \ numwords, " words, and ", numchars, "characters."source.close()

27

The set/frozenset containers

• We have seen several ways to store a collection of values.

• All are sequences– list, tuple, string (range produces a list)

• A sequence is an ordered collection of values• A set or frozenset is a collection of unique

values, with no particular order– unique = no duplicates– set is mutable– frozenset is immutable– elements in either are immutable

28

List Comprehension• Some actions are common enough to

warrant a shortened version. • result = [expression for identifier in

sequence if condition]– [ ] shows that a list is generated– expression says what the list elements are– identifier iterates through the elements in

the sequence– condition determines whether the

sequence item meets a requirement and is included in the result

29

List Comprehension• An example with no condition import nltkfrom nltk.book import text1print text1print "\n", "-----------------------"words=set(text1)print "Count of words in Moby Dick: ", len(sorted(words))print "Count of unique words in Moby Dick: ",\len(set([word.lower() for word in text1]))

• In the highlighted terms,• Expression is ???• Identifier is ???• Sequence is ???

Use of “set” removes duplicates

Example from nltk book

30

Functions• Define a collection of statements to be

executed as needed. • Parameters allow modification of the

values used during execution• We have seen a number of built-in

functions– examples --- ??

• Now we will create our own

31

Book example

def maxLength(stringSeq): longSoFar = "" #null string -- nothing between quotes for entry in stringSeq: print entry, " length is ", len(entry) if len(entry) > len(longSoFar): longSoFar = entry return longSoFar

ingredients = ['carbonated water', 'caramel color', 'caffeine', 'phosphoric acid',\'sodium saccharin', 'potassium benzoate', 'aspartame', 'potassium citrate',\'citric acid', 'dimethylpolysiloxane', 'natural flavors']concern = maxLength(ingredients)print concern

book slide

32

Parameters and arguments

book slide

33

Nested function calls

book slide

34

Optional parameters• Provide a default value to be used if none is

provided during the call.

def countdown(start = 10): for count in range(start, 0, -1) print count

countdown() #will countdown starting at 10countdown(5) #will countdown starting at 5

book slide

35

Conditional Statements with Duplicate Code.

#this has duplicate codeif destination == 'Missouri':

subtotal = sum(shoppingCart)tax = subtotal * 0.04225total = subtotal + tax

elif destination == 'Illinois':subtotal = sum(shoppingCart)tax = subtotal * 0.0625total = subtotal + tax

book slide

36

Conditional Statements: Better than Previous slide

subtotal = sum(shoppingCart)if destination == 'Missouri':

tax = subtotal * 0.04225elif destination == 'Illinois':

tax = subtotal * 0.0625total = subtotal + tax

book slide

37

Conditional Statements (Avoiding Duplicate Code)

# To improve readability call a function to # lookup tax rates.subtotal = sum(shoppingCart)tax = subtotal * lookupTaxRate(destination)total = subtotal + tax

book slide

38

Spot check• Practice 5.21 Define a function

sumOfSquares(n) that returns the sum of the first n positive integers,

k 2k=1

n

Recommended