Presentation is loading. Please wait.

Presentation is loading. Please wait.

Xiaojuan Cai Computational Thinking 1 Lecture 8 Loop Structure Xiaojuan Cai (蔡小娟) Fall, 2015.

Similar presentations


Presentation on theme: "Xiaojuan Cai Computational Thinking 1 Lecture 8 Loop Structure Xiaojuan Cai (蔡小娟) Fall, 2015."— Presentation transcript:

1 Xiaojuan Cai Computational Thinking 1 Lecture 8 Loop Structure Xiaojuan Cai (蔡小娟) cxj@sjtu.edu.cn Fall, 2015

2 Xiaojuan Cai Computational Thinking 2 Objective To understand the concepts of loops: definite loops: for indefinite loops: while To understand interactive loop, sentinel loop and end-of-file loop To understand the basic ideas of Boolean algebra

3 Xiaojuan Cai Computational Thinking 3 Roadmap For loops Indefinite loops Interactive, sentinel, file, nested loops Boolean algebra Other loop patterns: post-test, loop and a half

4 Xiaojuan Cai Computational Thinking 4 For loops: review Definite loop, syntax for in : Semantics The index variable takes on each successive value in, and execute once for each value Note: there might be infinite for loops, for example for x in a: a.append(x)

5 Xiaojuan Cai Computational Thinking 5 Roadmap For loops Indefinite loops Interactive, sentinel, file, nested loops Boolean algebra Other loop patterns: post-test, loop and a half

6 Xiaojuan Cai Computational Thinking 6 Motivating example Write a program computing the average of any size of numbers entered by the user. Algorithm pattern – accumulator (average1.py) Input the count of the numbers, n Initialize sum to 0 Loop n times Input a number, x Add x to sum Output average as sum/n

7 Xiaojuan Cai Computational Thinking 7 Indefinite loop What if we do not know how many numbers? The indefinite or conditional loop keeps iterating until certain conditions are met. while : condition? body yes no

8 Xiaojuan Cai Computational Thinking 8 Indefinite loop i = 0 while i <= 10: print i i = i + 1 The same output as this for loop: for i in range(11): print i

9 Xiaojuan Cai Computational Thinking 9 An infinite loop What should you do if you ’ re caught in an infinite loop? First, try pressing control-c If that doesn ’ t work, try control-alt-delete If that doesn ’ t work, push the reset button!

10 Xiaojuan Cai Computational Thinking 10 Interactive loops Average without knowing the exact number. set moredata to “yes” while moredata is “yes” get the next data item process the item ask user if there is moredata

11 Xiaojuan Cai Computational Thinking 11 Interactive loops Algorithm1 (average2.py) initialize sum to 0.0 initialize count to 0 set moredata to “yes” while moredata is “yes” input a number, x add x to sum add 1 to count ask user if there is moredata output sum/count

12 Xiaojuan Cai Computational Thinking 12 Sentinel loops A sentinel loop continues until reaching a special value that signals the end. This special value is called the sentinel. get the first data item while item is not the sentinel process the item get the next data item

13 Xiaojuan Cai Computational Thinking 13 Sentinel loops Algorithm 2 initialize sum to 0.0 initialize count to 0 input a number, x While x != sentinel add x to sum add 1 to count input another number, x output sum/count sentinel = a negative numbers (average3.py) sentinel = the empty string “” (average4.py)

14 Xiaojuan Cai Computational Thinking 14 File loops If the input size is large, you make a typo then you need to start over again in an interactive loop. File loops – read data from a file (average5.py) open a file f for line in f.readlines(): process the item

15 Xiaojuan Cai Computational Thinking 15 File loop + EOF sentinel EOF sentinel loop (average6.py) open a file f line = f.readline() while line != “” process the item line = f.readline() What if there is a blank line in the file? Blank line = ‘\n’, EOF = “”

16 Xiaojuan Cai Computational Thinking 16 Nested loop What if there are several data in one line (separated by commas)? open a file f line = f.readline() while line != “” for xStr in string.split(line, ","): sum = sum + eval(xStr) count = count + 1 line = f.readline()

17 Xiaojuan Cai Computational Thinking 17 Design nested loops Design the outer loop without worrying about what goes inside Design what goes inside, ignoring the outer loop. Put the pieces together, preserving the nesting.

18 Xiaojuan Cai Computational Thinking 18 Roadmap For loops Indefinite loops Interactive, sentinel, file, nested loops Boolean algebra Other loop patterns: post-test, loop and a half

19 Xiaojuan Cai Computational Thinking 19 Boolean expressions So far we’ve used Boolean expressions to compare two values We need more expressive expression. For example, two points are the same iff their x coordinates and y coordinates are same. This code is akward: if p1.getX() == p2.getX(): if p1.getY() == p2.getY(): else: else:

20 Xiaojuan Cai Computational Thinking 20 Boolean expressions and or not PQP and Q TTT TFF FTF FFF PQP or Q TTT TFT FTT FFF Pnot P TF FT

21 Xiaojuan Cai Computational Thinking 21 Compound expressions Consider a or not b and c How should this be evaluated? The order of precedence, from high to low, is relop, not, and, or. Use parentheses! (a or ((not b) and c))

22 Xiaojuan Cai Computational Thinking 22 Example: pingpong game Player A: a Player B: b Winning condition: One of the score is larger than or equal to 11 Win by at least 2 points (a >= 11 or b >= 11) and abs(a-b) >= 2

23 Xiaojuan Cai Computational Thinking 23 Boolean algebra and has properties similar to multiplication or has properties similar to addition 0 and 1 correspond to false and true. AlgebraBoolean algebra a * 0 = 0a and false == false a * 1 = aa and true == a a + 0 = aa or false == a

24 Xiaojuan Cai Computational Thinking 24 Boolean algebra True or a == True False and a == False Distributed: a or (b and c) == (a or b) and (a or c) a and (b or c) == (a and b) or (a and c) Double negatives cancel out: not(not a) == a DeMorgan’s laws: not(a or b) == (not a) and (not b) not(a and b) == (not a) or (not b)

25 Xiaojuan Cai Computational Thinking 25 Built-in types and bool response[0] == "y" or "Y" will always evaluate to True. Why? Python 2.7 has bool type with two values: True and False Older versions use 1 and 0 Zero int/float/long is interpreted as False, while non-zero int/float/long is True. An empty sequence is interpreted as False while any non-empty sequence is True.

26 Xiaojuan Cai Computational Thinking 26 Short-circuit x and y First evaluate x, if x is False, return False without evaluate y ! x or y First evaluate x, if x is True, return True without evaluate y ! shortCircuit.py

27 Xiaojuan Cai Computational Thinking 27 Flexibility ans = raw_input("What flavor [vanilla]? ") if ans != "": flavor = ans else: flavor = "vanilla" ans = raw_input("What flavor [vanilla]? ") if ans: flavor = ans else: flavor = "vanilla" ans = raw_input("What flavor [vanilla]? ") flavor = ans or "vanilla" flavor = raw_input("What flavor [vanilla]? ") or "vanilla"

28 Xiaojuan Cai Computational Thinking 28 Roadmap For loops Indefinite loops Interactive, sentinel, file, nested loops Boolean algebra Other loop patterns: post-test, loop and a half

29 Xiaojuan Cai Computational Thinking 29 Post-test loops Input validation The program asks for inputs until a valid value being entered. repeat input a number until number is >= 0 Python doesn’t have such built-in statement to do this condition? body yes no

30 Xiaojuan Cai Computational Thinking 30 Solutions Setting number to -1 number = -1 while number < 0: number = input("Enter a positive number: ") Infinite loop + break statement while True: number = input("Enter a positive number: ") if x >= 0: break Break statement makes Python immediately exit the enclosed loop

31 Xiaojuan Cai Computational Thinking 31 Loop and a half If we need to print some message when the input is negative. While loop: number = -1 while number < 0: number = input("Enter a positive number: ") if number < 0: print "The number was not positive“ Break statement while True: number = input("Enter a positive number: ") if x >= 0: break else: print "The number was not positive."

32 Xiaojuan Cai Computational Thinking 32 Loop and a half The loop exit is in the middle of the loop body. The use of break is mostly a matter of style and taste. The logic of a loop is hard to follow when there are multiple exits ( break statements).

33 Xiaojuan Cai Computational Thinking 33 Conclusion Decision structures allow a program to execute different sequences. if, if-else, if-elif-else statements Boolean expressions:, >=, ==, != Bool type: True, False Exception handling makes programs more “bulletproof”. Algorithm design: correct, efficient, and understandable


Download ppt "Xiaojuan Cai Computational Thinking 1 Lecture 8 Loop Structure Xiaojuan Cai (蔡小娟) Fall, 2015."

Similar presentations


Ads by Google