1 / 38

Control Structures in Python

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.

owen
Download Presentation

Control Structures in Python

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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 False True Block to execute when condition fails Block to execute when condition 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. Each block may contain any combination of instructions, function calls, etc. Condition test False True Block to execute when condition true

  9. Nested if example Consider this example code: values = range(27,150,4) print values x=raw_input("Enterx:") if x in values: print "x in value set", x else: 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 = 43 Run 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 • elifx>50

  11. values = range(27,150,4) print values strx=raw_input("Enterx:") x=int(strx) # or x=int(raw_input("Enterx: ")) if x in values: print "x in value set", x elifx> 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 body True 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: 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

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

  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 • Output Mike, 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 # 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, " 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. ", original print "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? ') whileanswer.lower() in ('y', 'yes'): #code for playing game ans= raw_input('Would you like to play again? ')

  24. Operation of the while Condition Loop body True 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 #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, " 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 orfrozenset is a collection of unique values, with no particular order • unique = no duplicates • set is mutable • frozensetis 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 nltk from nltk.book import text1 print text1 print "\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])) Use of “set” removes duplicates • In the highlighted terms, • Expression is ??? • Identifier is ??? • Sequence is ??? 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 inrange(start, 0, -1) print count countdown() #will countdown starting at 10 countdown(5) #will countdown starting at 5 book slide

  35. Conditional Statements with Duplicate Code. #this has duplicate code if destination == 'Missouri': subtotal = sum(shoppingCart) tax = subtotal * 0.04225 total = subtotal + tax elif destination == 'Illinois': subtotal = sum(shoppingCart) tax = subtotal * 0.0625 total = subtotal + tax book slide

  36. Conditional Statements: Better than Previous slide subtotal = sum(shoppingCart) if destination == 'Missouri': tax = subtotal * 0.04225 elif destination == 'Illinois': tax = subtotal * 0.0625 total = 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,

More Related