While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

Similar documents
Textbook. Topic 5: Repetition. Types of Loops. Repetition

C++ Programming: From Problem Analysis to Program Design, Third Edition

Theory of control structures

STUDENT LESSON A12 Iterations

COP 1220 Introduction to Programming in C++ Course Justification

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

Why Is Repetition Needed?

Condition Controlled Loops. Introduction to Programming - Python

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

To become familiar with array manipulation, searching, and sorting.

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Repetition and Loop Statements Chapter 5

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

Activity 6: Loops. Content Learning Objectives. Process Skill Goals

Software often repeats a set of instructions over and over again. This repetition continues until some condition is met.

Chapter 4: Programming with MATLAB

Activity 6: Loops. Content Learning Objectives. Process Skill Goals

[CHAPTER] 1 INTRODUCTION 1

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Outline. Announcements. Homework 2. Boolean expressions 10/12/2007. Announcements Homework 2 questions. Boolean expression

Java Outline (Upto Exam 2)

Fundamentals of Programming (Python) Control Structures. Sina Sajadmanesh Sharif University of Technology Fall 2017

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Chapter 5: Control Structures II (Repetition)

Iteration. CSE / ENGR 142 Programming I. Chapter 5. Motivating Loops. One More Type of Control Flow. What s Wrong with HW1?

CS 106 Introduction to Computer Science I

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Multi-Way Decisions. The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic

Flow Charts. Visual Depiction of Logic Flow

Textbook. Topic 6: Functions. Motivation. What is a Function? What s a function? How can we use functions to write better software?

CMSC 201 Spring 2017 Lab 12 Recursion

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea

CONTROL FLOW CREATING ALTERNATE PATHS OF EXECUTION USING: BRANCHING WHILE LOOPS FOR LOOPS

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Chapter 3: Modules. Starting Out with Programming Logic & Design. Second Edition. by Tony Gaddis

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Advanced Computer Programming

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter Goals. Contents LOOPS

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Flow Control. CSC215 Lecture

LOOPS. Repetition using the while statement

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Scheme of work Cambridge International AS & A Level Computing (9691)

CP222 Computer Science II. Recurrence Relations and Basic Sorting

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Loops / Repetition Statements

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Lecture 04 More Iteration, Nested Loops. Meet UTA Jarrett s dog Greta, lying in her nest

The Big Python Guide

Looping. Arizona State University 1

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

(Python) Chapter 3: Repetition

COP 1170 Introduction to Computer Programming using Visual Basic

Algorithms and Data Structures

Course: Programming 101 Introduction to Python. CIP Course Title / Code: Computer Programming / Duration: Part one of a two-semester series

Control Flow: Loop Statements

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

CHAPTER 3. Register allocation

Recursion. CSCI 112: Programming in C

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

Chapter 3. Iteration

Computing. Building Retention: What prior learning must be built upon/revisited and how will it be assessed? Term Cycle 1

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

Introduction to Programming Using Java (98-388)

Python Unit

6.001 Notes: Section 6.1

APCS Semester #1 Final Exam Practice Problems


Introduction to Computer Science with Python Course Syllabus

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Loops. CSE 114, Computer Science 1 Stony Brook University

Flow of Control: Loops

CS1150 Principles of Computer Science Loops (Part II)

8.3 Common Loop Patterns

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

SELECTION. (Chapter 2)

Condition Controlled Loops. Introduction to Programming - Python

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

What is an algorithm?

ENGR 1181 MATLAB 09: For Loops 2

Spring Semester 08, Dr. Punch. Exam #1 (2/12), form 1 A

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Making Decisions In Python

Transcription:

Recommended Readings Chapter 5 Topic 5: Repetition Are you saying that I am redundant? That I repeat myself? That I say the same thing over and over again? 1 2 Repetition So far, we have learned How to use variables Read values from the user Make decisions Compute a result Output a result Types of Loops Python includes two types of loops While Loops For Loops What if we want to perform a task several times? 3 4

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typically compound Needs to change one of the values being tested in the condition How do we compute the average of several numbers 5 6 While Loop Review Executes as long as some condition is true A pre-tested loop loop condition is tested before the loop executes the first time General form: while condition: statement(s) 7 8

Loop Terminology Body of the Loop: simple or compound statement that is repeated Loop Condition: a Boolean expression tested to determine if the loop will continue executing Initialization: Loop Terminology the process of placing starting values in variables before the loop Termination: the end of execution for the loop Pre-tested Loop: any loop where the loop condition is checked before the loop executes the first time 9 10 Loop Terminology Post-tested tested Loop: Any loop where the condition is not checked until the loop has executed once Infinite Loop: A loop that never terminates Another Using a while loop, compute n factorial 11 12

Initialization Errors Termination Errors Logic Errors Common Errors Tracing code: Tracing Examine each statement in sequence Perform whatever tasks the statement requires, recording values of interest Usually requires that the value of each variable is recorded Result of tracing could be the value of one or more variables, or the output generated 13 14 Another Factorial? n = input("enter a value for n: ") product = 1 factor = 0 while (factor <= n): factor = factor + 1 product = product * factor print "n! is", product While Loop Review Executes as long as some condition is True Pre-tested Executes zero or more times Generally need to initialize variables used in conditions before the loop need to change the value of at least one of these variables in the loop body 15 16

A counting loop For Loop Typically used when we know how many times we need to perform a task in advance A pre-tested loop General form: for variable in list: body Use a for loop to display the values from 3 to 10 For loop assigns a value from a list into a variable at the beginning of each loop iteration Construct a list with the range function 17 18 How Does a For Loop Work? List is examined If empty loop body does not execute control passes to statement after loop body If non-empty control variable is assigned next item in the list body of the loop executes control returns to the top of the loop Rewrite the factorial program using a for loop 19 20

Step Values Range is flexible With one parameter Counts from 0 to the number provided - 1 With two parameters Counts from the first number to the second number (exclusive), increasing by one each time Generates the empty list if the second number is less than the first With three parameters Counts from the first number to the second, increasing by the third 21 22 For Loops vs. While Loops What kind of loop would you use if: You know how many times the loop will execute You want to loop until some event occurs Is it possible that the body of a for loop will never execute? Is it possible that the body of a while loop will never execute? Nested Loops The body of a loop can be A simple statement A compound statement The body of the loop can contain another loop 23 24

Nested Loops Trace the output from the following program: for i in range(1,6): print i j = i while j < 5: print j j = j + 1 Bringing It All Together Write a simple number guessing game The computer will randomly choose a number between 1 and 100 The user will be asked to guess a number The computer will let the user know if the guess was too high or too low Goal: guess the correct number in as few guesses as possible 25 26 Bringing It All Together Improving our program: Should try and protect the user from themselves Don t let them guess a number smaller than the lowest remaining value Don t let them guess a number larger than the largest remaining value Don t count an out of range value as a guess Break and Continue Allow a loop iteration to end prematurely break Entire loop ends immediately Execution continues at the first statement after the loop body continue Current iteration ends immediately Execution returns to the top of the loop In a for loop, the next item in the list is used 27 28

Wrapping Up Two types of loops available While loops For loops Both types are pre-tested Will execute zero or more times Loops can be nested, mixed with other statement types Where Are We Going? Our number guessing game had a problem Many lines of code in one place Starting to become more difficult to enhance and debug Solution? Use functions to break our solution into pieces that each perform a specific task 29 30