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

Slides:



Advertisements
Similar presentations
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Advertisements

CS0004: Introduction to Programming Repetition – Do Loops.
James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
Python Programming: An Introduction To Computer Science
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 5: Control Structures II (Repetition)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Python Programming: An Introduction To Computer Science
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Iteration  Iteration just means we keep doing the same thing over and over until some threshold is reached, until a condition has been met.  We’ve already.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 5: Control Structures II (Repetition)
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Xiaojuan Cai Computational Thinking 1 Lecture 7 Decision Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Tutorial 9 Iteration. Reminder Assignment 8 is due Wednesday.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II (Repetition)
Python: Control Structures
Chapter 5: Control Structures II
Control Structures II (Repetition)
JavaScript: Control Statements.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
子夜吳歌 ~ 李白 長安一片月, 萬戶擣衣聲; 秋風吹不盡, 總是玉關情。 何日平胡虜, 良人罷遠征。
Chapter 6: Repetition Statements
子夜吳歌 ~ 李白 長安一片月, 萬戶擣衣聲; 秋風吹不盡, 總是玉關情。 何日平胡虜, 良人罷遠征。
Chapter 5: Control Structures II (Repetition)
Another Example Problem
Presentation 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 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)

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 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 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 and or not PQP and Q TTT TFF FTF FFF PQP or Q TTT TFT FTT FFF Pnot P TF FT

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. AlgebraBoolean algebra a * 0 = 0a and false == false a * 1 = aa and true == a a + 0 = aa 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 number until 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 statement while 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 = -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."

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