9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

Slides:



Advertisements
Similar presentations
CS0004: Introduction to Programming Repetition – Do Loops.
Advertisements

LOOP / REPETITION while loop. for loop do/while loop We assume that loops are not meant to be infinite. That is, there should always be a way out of the.
Objectives In this chapter, you will learn about:
Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Chapter 5: Control Structures II (Repetition)
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops and Files.
Python Programming: An Introduction To Computer Science
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
Python Programming: An Introduction To Computer Science
Fundamentals of Python: From First Programs Through Data Structures
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
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.
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.
CS 127 Writing Simple Programs.  Stages involved  Analyze the problem  Understand as much as possible what is trying to be solved  Determine Specifications.
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.
Chapter 5: Control Structures: Iteration Visual Basic.NET Programming: From Problem Analysis to Program Design.
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Chapter 5: Control Structures: Iteration Visual Basic.NET Programming: From Problem Analysis to Program Design.
CPS120 Introduction to Computer Science Iteration (Looping)
Xiaojuan Cai Computational Thinking 1 Lecture 8 Loop Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
1 Fall 2009ACS-1903 Ch 4 Loops and Files while loop do-while loop for loop Other topics later on …
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
REPETITION CONTROL STRUCTURE
Python: Control Structures
Lesson 05: Iterations Class Chat: Attendance: Participation
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Chapter 5: Repetition Structures
( Iteration / Repetition / Looping )
While Loops in Python.
Topics Introduction to Repetition Structures
CS190/295 Programming in Python for Life Sciences: Lecture 6
Chapter 6: Repetition Structures
Chapter 5: Repetition Structures
子夜吳歌 ~ 李白 長安一片月, 萬戶擣衣聲; 秋風吹不盡, 總是玉關情。 何日平胡虜, 良人罷遠征。
3. Decision Structures Rocky K. C. Chang 19 September 2018
子夜吳歌 ~ 李白 長安一片月, 萬戶擣衣聲; 秋風吹不盡, 總是玉關情。 何日平胡虜, 良人罷遠征。
Topics Introduction to Repetition Structures
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Another Example Problem
Based on slides created by Bjarne Stroustrup & Tony Gaddis
While Loops in Python.
Presentation transcript:

9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)

Objectives To understand the concepts of definite and indefinite loops as they are realized in the Python for and while statements. To understand the programming patterns interactive loop and sentinel loop and their implementations using a Python while statement. To understand the programming pattern end-of-file loop and ways of implementing such loops in Python.

For Loops: A Quick Review The for statement allows us to iterate through a sequence of values. for in : The loop index variable var takes on each successive value in the sequence, and the statements in the body of the loop are executed once for each value.

Indefinite Loops The for loop is a definite loop, meaning that the number of iterations is determined when the loop starts. We can ’ t use a definite loop unless we know the number of iterations ahead of time. The indefinite or conditional loop keeps iterating until certain conditions are met.

Indefinite Loops while : condition is a Boolean expression, just like in if statements. The body is a sequence of one or more statements. Semantically, the body of the loop executes repeatedly as long as the condition remains true. When the condition is false, the loop terminates.

A Pre-test Loop

An example Here ’ s an example of using a while loop to print out range(10). i = 0 while i <= 9: print(i) i = i + 1 The code has the same output as this for loop: for i in range(10): print i

EXERCISE 9.1 Use a while loop to print out range(2, 10, 2).

EXERCISE 9.2 Try i = 0 while i <= 9: print(i)

Interactive Loops # average2.py # A program to average a set of numbers # Illustrates interactive loop with two accumulators moredata = "yes" sum = 0.0 count = 0 while moredata[0] == 'y': x = int(input("Enter a number >> ")) sum = sum + x count = count + 1 moredata = input("Do you have more numbers (yes or no)? ") print ("\nThe average of the numbers is", sum / count)

EXERCISE 9.3 One problem with the program is that if you type too fast, you may enter a number as an answer to the yes/no question. What will the program respond to this "error"? How will you modify the program to rectify the response?

Sentinel Loops A sentinel loop continues to process data until reaching a special value that signals the end. This special value is called the sentinel. The sentinel must be distinguishable from the data since it is not processed as part of the data. get the first data item while item is not the sentinel process the item get the next data item

EXERCISE 9.4 Apply the sentinel approach to implementing the program for returning the average on slide 10.

File Loops # average5.py # Computes the average of numbers listed in a file. def main(): fileName = input("What file are the numbers in? ") infile = open(fileName,'r') sum = 0.0 count = 0 for line in infile: sum = sum + eval(line) count = count + 1 print ("\nThe average of the numbers is", sum / count)

EXERCISE 9.5 Instead of using a list of lines, you could also the readline() method to read one line at a time. In this case, you need to detect the end- of-file yourself. The sentinel for the end of file is line == "". Try to implement it.

Nested Loops Suppose we change our specification to allow any number of numbers on a line in the file (separated by commas), rather than one per line. sum = 0.0 count = 0 for line in infile: # update sum and count for values in line # Since we have multiple items to process, # we can use another loop for this. print ("\nThe average of the numbers is", sum / count)

EXERCISE 9.6 Implement the remaining codes for the program in the previous slide.

Designing Nested Loops Break the problem into two parts. The first is to process line by line (outer loop). The second is to process the items on each line (inner loop). Note that the two parts are not inter-dependent.

Post-Test Loop Say we want to write a program that is supposed to get a nonnegative number from the user. If the user types an incorrect input, the program asks for another value. This process continues until a valid value has been entered. This process is input validation.

Post-Test Loop repeat get a number from the user until number is >= 0

Post-Test Loop Python doesn ’ t have a built-in statement to do this, but we can do it with a slightly modified while loop. We could simulate a post-test loop by number = -1 while number < 0: number = eval(input("Enter a positive number: "))

Using a break Some programmers prefer to simulate a post-test loop by using the Python break statement. Executing break causes Python to immediately exit the enclosing loop. For example, while True: number = eval(input("Enter a positive number: ")) if number >= 0: break # Exit loop if number is valid Avoid using break often within loops, because the logic of a loop is hard to follow when there are multiple exits.

EXERCISE 9.7 Enhance the codes in the previous page by printing out an error message if the input is not valid.

Loop and a Half while True: get next data item if the item is the sentinel: break process the item

END