control structures conditionals if statements format
play

Control Structures Conditionals: If-Statements Format Example if - PowerPoint PPT Presentation

Lecture 6 Control Structures Conditionals: If-Statements Format Example if < boolean-expression >: # Put x in z if it is positive < statement > if x > 0: z = x < statement > Execution : if <b oolean-expression


  1. Lecture 6 Control Structures

  2. Conditionals: If-Statements Format Example if < boolean-expression >: # Put x in z if it is positive < statement > if x > 0: … z = x < statement > Execution : if <b oolean-expression > is true, then execute all of the statements indented directly underneath (until first non-indented statement) 9/25/15 Control Structures 2

  3. Conditionals: If-Else-Statements Format Example if < boolean-expression >: # Put max of x, y in z < statement > if x > y: … z = x else : else : < statement > z = y … Execution : if <b oolean-expression > is true, then execute statements indented under if; otherwise execute the statements indented under elsec 9/25/15 Control Structures 3

  4. Conditionals: If-Elif-Else-Statements Format Example if < boolean-expression >: # Put max of x, y, z in w < statement > if x > y and x > z: … w = x elif < boolean-expression >: elif y > z: < statement > … w = y … else : else : w = z < statement > … 9/25/15 Control Structures 4

  5. Conditionals: If-Elif-Else-Statements Format Notes on Use if < boolean-expression >: • No limit on number of elif < statement > § Can have as many as want … § Must be between if , else elif < boolean-expression >: • The else is always optional < statement > § if - elif by itself is fine … … • Booleans checked in order else : § Once it finds a true one, it < statement > skips over all the others … § else means all are false 9/25/15 Control Structures 5

  6. Conditional Expressions Format Example # Put max of x, y in z e1 if bexp else e2 z = x if x > y else y • e1 and e2 are any expression • bexp is a boolean expression • This is an expression! expression, not statement 9/25/15 Control Structures 6

  7. Program Flow vs. Local Variables def max(x,y): • temp is needed for swap """Returns: max of x, y""" § x = y loses value of x # swap x, y § “Scratch computation” # put the larger in y § Primary role of local vars 1 if x > y: • max(3,0) : 2 temp = x max 3 x = y 4 y = temp x y 0 3 temp 3 5 return y 9/25/15 Control Structures 7

  8. Program Flow vs. Local Variables def max(x,y): • Value of max(3,0) ? """Returns: max of x, y""" A: 3 # swap x, y B: 0 # put the larger in y C: Error! if x > y: D: I do not know temp = x x = y y = temp return temp 9/25/15 Control Structures 8

  9. Program Flow vs. Local Variables def max(x,y): • Value of max(3,0) ? """Returns: max of x, y""" A: 3 CORRECT # swap x, y B: 0 # put the larger in y C: Error! if x > y: D: I do not know temp = x x = y • Local variables last until y = temp § They are deleted or § End of the function return temp • Even if defined inside if 9/25/15 Control Structures 9

  10. Program Flow vs. Local Variables def max(x,y): • Value of max(0,3) ? """Returns: max of x, y""" A: 3 # swap x, y B: 0 # put the larger in y C: Error! if x > y: D: I do not know temp = x x = y y = temp return temp 9/25/15 Control Structures 10

  11. Program Flow vs. Local Variables def max(x,y): • Value of max(0,3) ? """Returns: max of x, y""" A: 3 # swap x, y B: 0 # put the larger in y C: Error! CORRECT if x > y: D: I do not know temp = x x = y • Variable existence y = temp depends on flow • Understanding flow return temp is important in testing 9/25/15 Control Structures 11

  12. Local Variables Revisited def max(x,y): • Never refer to a variable """Returns: max of x, y""" that might not exist # swap x, y • Variable “scope” # put larger in temp § Block (indented group) if x > y: where it was first assigned temp = x First assigned § Way to think of variables; x = y not actually part of Python y = temp • Rule of Thumb : Limit variable usage to its scope return temp Outside scope 9/25/15 Control Structures 12

  13. Local Variables Revisited def max(x,y): • Never refer to a variable """Returns: max of x, y""" that might not exist # swap x, y • Variable “scope” # put larger in temp § Block (indented group) temp = y First assigned where it was first assigned if x > y: § Way to think of variables; temp = x not actually part of Python • Rule of Thumb : Limit return temp Inside scope variable usage to its scope 9/25/15 Control Structures 13

  14. Variation on max def max(x,y): Which is better? """Returns: Matter of preference max of x, y""" if x > y: return x There are two returns ! else: But only one is executed return y 9/25/15 Control Structures 14

  15. For Loops: Processing Sequences # Print contents of seq The for-loop: x = seq[0] for x in seq: print x print x x = seq[1] print x … • Key Concepts x = seq[len(seq)-1] § loop sequence: seq print x § loop variable : x • Remember : § body : print x § Cannot program … § Also called repetend § Reason for recursion 9/25/15 Control Structures 15

  16. For Loops: Processing Sequences • loop sequence: seq The for-loop: • loop variable : x for x in seq: • body : print x print x To execute the for-loop: 1. Check if there is a “next” element of loop sequence True seq has 2. If not, terminate execution put next more elts elt in x 3. Otherwise, put the element in the loop variable 4. Execute all of the body False print x 5. Repeat as long as 1 is true 9/25/15 Control Structures 16

  17. Example: Summing the Elements of a List def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist is a list of all numbers (either floats or ints)""" # Create a variable to hold result (start at 0) # Add each list element to variable # Return the variable 9/25/15 Control Structures 17

  18. Example: Summing the Elements of a List def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist is a list of all numbers (either floats or ints)""" result = 0 • loop sequence: thelist for x in thelist: result = result + x • loop variable : x • body : result=result+x return result 9/25/15 Control Structures 18

  19. Example: Summing the Elements of a List def sum(thelist): """Returns: the sum of all elements in thelist Precondition: thelist is a list of all numbers (either floats or ints)""" Accumulator result = 0 variable • loop sequence: thelist for x in thelist: result = result + x • loop variable : x • body : result=result+x return result 9/25/15 Control Structures 19

  20. For Loops and Conditionals def num_ints(thelist): """Returns: the number of ints in thelist Precondition: thelist is a list of any mix of types""" # Create a variable to hold result (start at 0) # for each element in the list… # check if it is an int # add 1 if it is # Return the variable 9/25/15 Control Structures 20

  21. For Loops and Conditionals def num_ints(thelist): """Returns: the number of ints in thelist Precondition: thelist is a list of any mix of types""" result = 0 for x in thelist: if type(x) == int: Body result = result+1 return result 9/25/15 Control Structures 21

  22. Modifying the Contents of a List def add_one(thelist): """(Procedure) Adds 1 to every element in the list Precondition: thelist is a list of all numbers (either floats or ints)""" for x in thelist: DOES NOT WORK! x = x+1 # procedure; no return 9/25/15 Control Structures 22

  23. More Complex For-Loops • Combine with a counter • Nest conditionals inside § Variable that increments § Body is all indented code each time body executed § Can put other control § Tracks position in seq structures inside the body • Example : • Example : cnt = 0 nints = 0 # num of ints for x in seq: for x in seq: print `x`+' at '+`cnt` if type(x) == int: cnt = cnt + 1 # incr nints = nints + 1 9/25/15 Control Structures 23

  24. for-loops: Beyond Sequences def blanklines(fname): • Work on iterable objects """Return: # blank lines in file fname § Object with an ordered Precondition: fname is a string""" collection of data # open makes a file object § This includes sequences file = open('myfile.txt') § But also much more # Accumulator count = 0 • Examples : for line in file: # line is a string § Text Files (built-in) if len(line) == 0: # line is blank § Web pages ( urllib2 ) count = count+1 • 2110 : learn to design f.close() # close file when done return count custom iterable objects 9/25/15 Control Structures 24

  25. Beyond Sequences: The while-loop while < condition >: statement 1 repetend or body … statement n • Relationship to for-loop § Broader notion of true condition “still stuff to do” repetend § Must explicitly ensure false condition becomes false 9/25/15 Control Structures 25

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend