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

Similar documents
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

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

Topic 7: Lists, Dictionaries and Strings

LOOPS. Repetition using the while statement

[CHAPTER] 1 INTRODUCTION 1

Notes on Chapter 1 Variables and String

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

Topic 2: Introduction to Programming

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

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

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

(Python) Chapter 3: Repetition

Theory of control structures

Textbook. Topic 8: Files and Exceptions. Files. Types of Files

STUDENT LESSON A12 Iterations

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

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

COP 1220 Introduction to Programming in C++ Course Justification

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

Why Is Repetition Needed?

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

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.

Algorithms and Data Structures

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

Repetition and Loop Statements Chapter 5

Fundamentals of Programming. Week 1 - Lecture 3: Loops

CS 106 Introduction to Computer Science I

Java Outline (Upto Exam 2)

Advanced Computer Programming

Module 06. Topics: Iterative structure in Python Readings: ThinkP 7. CS116 Spring : Iteration

6.001 Notes: Section 6.1

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

CMSC 201 Spring 2017 Lab 12 Recursion

Lab 3: Sampling Distributions

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

Control Structures 1 / 17

Control Structures II. Repetition (Loops)

Common Loop Algorithms 9/21/16 42

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

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

The while Loop 4/6/16 4

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

Control structure: Repetition - Part 3

COMS 469: Interactive Media II

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

Python Unit

Welcome to Starting Out with Programming Logic and Design, Third Edition.

Chapter 4: Programming with MATLAB

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

Control Flow: Loop Statements

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

CIS 130 Exam #2 Review Suggestions

Making Decisions In Python

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Java Software Solutions for AP Computer Science 3rd Edition, Lewis et al. 2011

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

Unit 7: Algorithms and Python CS 101, Fall 2018

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

CMPS Sample Syllabus. DAY SESSION TOPIC COVERED/WORK DONE 1 (Monday) Morning

SBT 645 Introduction to Scientific Computing in Sports Science #3

CMSC201 Computer Science I for Majors

B. Subject-specific skills B1. Problem solving skills: Supply the student with the ability to solve different problems related to the topics

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?

mith College Computer Science CSC103 How Computers Work Week 7 Fall 2017 Dominique Thiébaut

ElseIf: Another Conditional Statement

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

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

APCS Semester #1 Final Exam Practice Problems

Flow Charts. Visual Depiction of Logic Flow

Loops. Upsorn Praphamontripong. CS 1110/CS 1111 Introduction to Programming Spring 2018

Iteration Part 1. Motivation for iteration. How does a for loop work? Execution model of a for loop. What is Iteration?

Introduction to Computer Science with Python Course Syllabus

Flow of Control: Loops

Loops. Variable Scope Remapping Nested Loops. Donald Judd. CS Loops 1. CS Loops 2

This document describes how I implement the Newton method using Python and Fortran on the test function f(x) = (x 1) log 10 (x).

CHAPTER 3. Register allocation

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

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

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

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

Boca Raton Community High School AP Computer Science A - Syllabus 2009/10

Module 3: Strings and Input/Output

Computer Hardware 6. The

KOMAR UNIVERSITY OF SCIENCE AND TECHNOLOGY (KUST)

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

Advanced Algorithms and Data Structures

Chapter Goals. Contents LOOPS

Planning: Wrap up CSP Planning Logic: Intro

Repetition, Looping CS101

Loop structures and booleans

Iteration -- Once Is Not Enough

Transcription:

Textbook Topic 5: Repetition Are you saying that I am redundant? That I repeat myself? That I say the same thing over and over again? Strongly Recommended Exercises The Python Workbook: 64, 69, 74, and 79 Recommended Exercises The Python Workbook: 62, 65, 75, 77, 78 and 80 Course Website: Loop Exercises Recommended Readings Starting Out with Python Chapter 5 (2 nd Ed.) / Chapter 4 (3 rd Ed. and 4 th Ed.) 1 2 So far, we have learned How to use variables Read values from the user Make decisions Compute a result Output a result Repetition 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 Loop Terminology Initialization: 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 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 Other Logic Errors Common Errors Tracing Tracing code: 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 = int(input("enter a value for n: ")) result = 1 term = 0 while (term <= n): term = term + 1 result = result * term 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 print("n! is", result) 15 16

For Loop A counting 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 up to and including 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 every value has already been processed loop body does not execute control passes to statement after loop body If unprocessed values remain variable is assigned next item in the list body of the loop executes control returns to the top of the loop list is examined to see if the body should run again 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 or equal to the first With three parameters Counts from the first number to the second (exclusive), increasing by the third 21 Create a program that generates a smooth color gradient from black to 255 192 64 22 For Loops vs. While Loops Nested 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? 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: Nested Loop Convert an image from color to grayscale for i in range(1,6): print(i) j = i while j < 5: print(j) j = j + 1 25 26 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 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 27 28

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 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 29 30 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 31