Control Structures in Python So Far We can




















![Danger – modifying iteration variable original = ["A", "B", "C", "D", "E", "F"] for Danger – modifying iteration variable original = ["A", "B", "C", "D", "E", "F"] for](https://slidetodoc.com/presentation_image_h2/8a30c1198fc542f64d712ed328313388/image-21.jpg)

















- Slides: 38

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. • Control structures in a language allow these 2

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 3

IF … • Simplest control – Do some specified instructions if a given condition is true if <condition>: <instruction(s) to execute> Note: indentation and punctuation are required. – 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> 4

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. 5

The Flow Chart False Block to execute when condition fails Condition test True Block to execute when condition true 6

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

Each block may contain any combination of instructions, function calls, etc. False Condition test True Block to execute when condition true 8

Nested if example Consider this example code: Understand what it is supposed to do? values = range(27, 150, 4) Predict the output, x = 43 print values Run it x=raw_input("Enter x: ") if x in values: Explain what is wrong print "x in value set", x else: if x> 50: print "new x greater than 50" else: print "new x less than 50" 9

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 10

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

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 10 to 15 minutes should do it both sets. 12

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. 13

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 14

Flowchart for loop Set iteration variable to initial or next value variable in range? True Loop body False Skip loop body if initial iteration variable value is out of range. 15

Input from a file • Built-in file class – Two ways to input a line from the file: • line=source. readline() • for line in source: where line and source are local names, source previously defined Note – no explicit read in the for loop filename=raw_input('File to read: ') source = file(filename) #Access is read-only for line in source: print line 16

Iterating through a string teststring = "When in the course of human events, it becomes necessary. . . " countc = 0 for c in teststring: if c == "a": countc +=1 print "Number of c's in the string: ", countc 17

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. 18

Stepping through the list again cousins=["Mike", "Carol", "Frank", "Ann", "Jim", "Pat", "Franny”, "Elizabeth", "Richard", "Sue"] for step in range(len(cousins)): print cousins[step]+", ”, • Output Mike, Carol, Frank, Ann, Jim, Pat, Franny, Elizabeth, Richard, Sue, 19

Stepping through a file # Based on Figure 8. 4 of Object Oriented Programming in # Python filename=raw_input("Enter filename: ") source=file(filename) numlines = numwords = numchars = 0 for line in source: numlines += 1 numwords += len(line. split()) numchars +=len(line) print line print "The file contains ", numlines, ", numwords, " words, and ", numchars, "characters. " source. close() 20
![Danger modifying iteration variable original A B C D E F for Danger – modifying iteration variable original = ["A", "B", "C", "D", "E", "F"] for](https://slidetodoc.com/presentation_image_h2/8a30c1198fc542f64d712ed328313388/image-21.jpg)
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. append(entry) print "List with ", entry, " appended. ", original print "List at end of loop: n ", original Predict the output 21

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. 22

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? ') 23

Operation of the while Condition True Loop body 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. 24

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. 25

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

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 27

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 28

List Comprehension • An example with no condition import nltk from nltk. book import text 1 Use of “set” removes print text 1 duplicates print "n", "------------" words=set(text 1) 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 text 1])) Example from nltk book • In the highlighted terms, • Expression is ? ? ? • Identifier is ? ? ? • Sequence is ? ? ? 29

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 30

Book example def max. Length(string. Seq): long. So. Far = "" #null string -- nothing between quotes for entry in string. Seq: print entry, " length is ", len(entry) if len(entry) > len(long. So. Far): long. So. Far = entry return long. So. Far ingredients = ['carbonated water', 'caramel color', 'caffeine', 'phosphoric acid', 'sodium saccharin', 'potassium benzoate', 'aspartame', 'potassium citrate', 'citric acid', 'dimethylpolysiloxane', 'natural flavors'] concern = max. Length(ingredients) print concern book slide 31

Parameters and arguments book slide 32

Nested function calls book slide 33

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 countdown() #will countdown starting at 10 countdown(5) #will countdown starting at 5 book slide 34

Conditional Statements with Duplicate Code. #this has duplicate code if destination == 'Missouri': subtotal = sum(shopping. Cart) tax = subtotal * 0. 04225 total = subtotal + tax elif destination == 'Illinois': subtotal = sum(shopping. Cart) tax = subtotal * 0. 0625 total = subtotal + tax book slide 35

Conditional Statements: Better than Previous slide subtotal = sum(shopping. Cart) if destination == 'Missouri': tax = subtotal * 0. 04225 elif destination == 'Illinois': tax = subtotal * 0. 0625 total = subtotal + tax book slide 36

Conditional Statements (Avoiding Duplicate Code) # To improve readability call a function to # lookup tax rates. subtotal = sum(shopping. Cart) tax = subtotal * lookup. Tax. Rate(destination) total = subtotal + tax book slide 37

Spot check • Practice 5. 21 Define a function sum. Of. Squares(n) that returns the sum of the first n positive integers, 38