xiaojuan cai computational thinking 1 lecture 8 loop structure xiaojuan cai (蔡小娟)...
TRANSCRIPT
Xiaojuan Cai Computational Thinking 1
Lecture 8
Loop Structure
Xiaojuan Cai(蔡小娟)
Fall, 2015
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
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
Xiaojuan Cai Computational Thinking 4
For loops: review• Definite loop, syntax
for <var> in <sequence>:
<body>
• Semantics
• The index variable <var> takes on each successive value in
<sequence>, and execute <body> once for each value
• Note: there might be infinite for loops, for example
for x in a:
a.append(x)
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
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
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>
condition?
body
yes
no
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
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!
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
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
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
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)
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
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 = “”
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()
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.
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
Xiaojuan Cai Computational Thinking 19
Boolean expressions• So far we’ve used Boolean expressions to compare two
values <expr><relop><expr>
• 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:
Xiaojuan Cai Computational Thinking 20
Boolean expressions• <expr> and <expr>
• <expr> or <expr>
• not <expr>
P Q P and QT T TT F FF T FF F F
P Q P or Q
T T TT F TF T TF F F
P not PT FF T
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))
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
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.
Algebra Boolean algebra
a * 0 = 0 a and false == false
a * 1 = a a and true == a
a + 0 = a a or false == a
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)
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.
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
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"
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
Xiaojuan Cai Computational Thinking 29
Post-test loops
• Input validation
• The program asks for inputs
until a valid value being entered.
• repeat input a numberuntil number is >= 0
• Python doesn’t have such built-in
statement to do this
condition?
body
yes
no
Xiaojuan Cai Computational Thinking 30
Solutions• Setting number to -1
number = -1
while number < 0:
number = input("Enter a positive number: ")
• Infinite loop + break statementwhile True:
number = input("Enter a positive number: ")
if x >= 0: break
• Break statement makes Python immediately
exit the enclosed loop
Xiaojuan Cai Computational Thinking 31
Loop and a half• If we need to print some message when the input is
negative.
• While loop:number = -1while number < 0: number = input("Enter a positive number: ") if number < 0: print "The number was not positive“
• Break statementwhile True: number = input("Enter a positive number: ") if x >= 0: break else: print "The number was not positive."
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).
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