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

Similar documents
QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Two-way selection. Branching and Looping

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

Computer Science 217

Python Programming: An Introduction To Computer Science

UEE1302 (1102) F10 Introduction to Computers and Programming

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CHAPTER 18 Programming Your App to Make Decisions: Conditional Blocks

ALGORITHMS AND FLOWCHARTS

Colored Hats and Logic Puzzles

CSC 221: Computer Programming I. Fall 2011

Python Loops and String Manipulation

Visual Logic Instructions and Assignments

While Loop. 6. Iteration

The While Loop. Objectives. Textbook. WHILE Loops

Test Case Design Techniques

Multiplying Integers. Lesson Plan

6. Control Structures

Programming Your App to Make Decisions: Conditional Blocks

Database Programming with PL/SQL: Learning Objectives

Writing Control Structures

Computer Programming I

Regular Expressions and Automata using Haskell

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Test case design techniques I: Whitebox testing CISS

LOOPS CHAPTER CHAPTER GOALS

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Computer Programming I & II*

Computational Mathematics with Python

Senem Kumova Metin & Ilker Korkmaz 1

AP Stats - Probability Review

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

CSC 180 H1F Algorithm Runtime Analysis Lecture Notes Fall 2015

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Introduction to Python

Supplemental Worksheet Problems To Accompany: The Pre-Algebra Tutor: Volume 1 Section 1 Real Numbers

Lecture 2 Notes: Flow of Control

Tom wants to find two real numbers, a and b, that have a sum of 10 and have a product of 10. He makes this table.

Opposites are all around us. If you move forward two spaces in a board game

CISC - Curriculum & Instruction Steering Committee. California County Superintendents Educational Services Association

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

Computational Mathematics with Python

0.8 Rational Expressions and Equations

JavaScript: Control Statements I

6.080/6.089 GITCS Feb 12, Lecture 3

Problem Solving Basics and Computer Programming

Lab 11. Simulations. The Concept

14:440:127 Introduction to Computers for Engineers. Notes for Lecture 06

River Dell Regional School District. Computer Programming with Python Curriculum

WAYNESBORO AREA SCHOOL DISTRICT CURRICULUM INTRODUCTION TO COMPUTER SCIENCE (June 2014)

Lecture 4: Writing shell scripts

Fundamentals of Probability

1 Description of The Simpletron

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Selection Statements

Binary Adders: Half Adders and Full Adders

5. Tutorial. Starting FlashCut CNC

FACE TO FACE SELLING SKILLS MODULE 6 CUSTOMER NEEDS ANALYSIS Pre-Tutorial ACCOUNT MANAGER S WORKBOOK

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

There are a number of superb online resources as well that provide excellent blackjack information as well. We recommend the following web sites:

Unit 1 Number Sense. In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions.

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

KS3 Computing Group 1 Programme of Study hours per week

Objective. Materials. TI-73 Calculator

Playing with Numbers

Iteration CHAPTER 6. Topic Summary

Chapter 13: Program Development and Programming Languages

Some programming experience in a high-level structured programming language is recommended.

Chapter 2 Writing Simple Programs

Programming MS Excel in Visual Basic (VBA)

Random Fibonacci-type Sequences in Online Gambling

Clock Arithmetic and Modular Systems Clock Arithmetic The introduction to Chapter 4 described a mathematical system

Test case design techniques I: Whitebox testing CISS

Zero-knowledge games. Christmas Lectures 2008

MATLAB Programming. Problem 1: Sequential

Welcome to Introduction to programming in Python

CHM 579 Lab 1: Basic Monte Carlo Algorithm

Windows PowerShell Essentials

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Hoover High School Math League. Counting and Probability

VHDL Test Bench Tutorial

Using Flow Control with the HEAD Recorder

How To Program In Scheme (Prolog)

Deep Agile Blending Scrum and Extreme Programming. Jeff Sutherland Ron Jeffries

[Refer Slide Time: 05:10]

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control

Using games to support. Win-Win Math Games. by Marilyn Burns

VB.NET Programming Fundamentals

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

Python Evaluation Rules

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Transcription:

Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code. The Need For Repetition (Loops) Writing out a simple counting program (1 3). print 1 print 2 print 3

The Need For Repetition (2) Simple program but what if changes need to be made? The source code must be re-edited and re-compiled each time that a change is needed. What if you need the program to count many times? Basic Structure Of Loops 1) Initialize the control a) Control typically a variable that determines whether or not the loop executes or not. 2) Testing the control against a stopping condition 3) Executing the body of the loop (the part to be repeated) 4) Update the value of the control

Types Of Loops 1.Pre-test loops Check the stopping condition before executing the body of the loop. The loop executes zero or more times. 2.Post-test loops Checking the stopping condition after executing the body of the loop. The loop executes one or more times. Pre-Test Loops 1. Initialize loop control 2. Check if the stopping condition has been met a. If it s been met then the loop ends b. If it hasn t been met then proceed to the next step 3. Execute the body of the loop (the part to be repeated) 4. Update the loop control Initialize loop control Condition met? No Execute body Update control Yes 5. Go to step 2 After the loop (done looping)

Post-Test Loops (Not Implemented In Python) 1. Initialize loop control (sometimes not needed because initialization occurs when the control is updated) 2. Execute the body of the loop (the part to be repeated) 3. Update the loop control 4. Check if the stopping condition has been met a. If it s been met then the loop ends b. If it hasn t been met then return to step 2. No Initialize loop control Execute body Update control Condition met? Yes After the loop (done looping) Pre-Test Loops In Python 1. While 2. For Characteristics: 1. The stopping condition is checked before the body executes. 2. These types of loops execute zero or more times.

Post-Loops In Python None: this type of looping construct has not been implemented with this language. Characteristics: The stopping condition is checked after the body executes. These types of loops execute one or more times. The While Loop This type of loop can be used if it s not in advance how many times that the loop will repeat (most powerful type of loop). Format: (Simple) while (Boolean expression): body (Compound) while (Boolean expression) Boolean operator (Boolean expression): body

The While Loop (2) Example: (The full program can be found in Unix under /home/courses/217/examples/loops/while1.p) i = 1 while (i <= 5): print "i =", i i += 1 The While Loop (2) Example: (The full program can be found in Unix under /home/courses/217/examples/loops/while1.p) i = 1 while (i <= 5): print "i =", i i += 1 1) Initialize control 2) Check condition 3) Execute body 4) Update control

Tracing The While Loop Execution >python while1.py Variable i The For Loop Typically used when it is known in advance how many times that the loop will execute (counting loops). Syntax: for <name of loop control> in <something that can be iterated>: body Example: (The full program can be found in Unix under /home/courses/217/examples/loops/for1.p) for i in range (1, 6, 1): total = total + i print "i = ", i, "\t total = ", total

The For Loop Typically used when it is known in advance how many times that the loop will execute (counting loops). Syntax: for <name of loop control> in <something that can be iterated>: body 1) Initialize control Example: (The full program can be found in Unix under /home/courses/217/examples/loops/for1.p) 2) Check condition for i in range (1, 6, 1): total = total + i print "i = ", i, "\t total = ", total 4) Update control 3) Execute body Tracing The First For Loop Example Execution >python for1.py Variables i total

Counting Down With A For Loop Example: (The full program can be found in Unix under /home/courses/217/examples/loops/for2.p) for i in range (5, 0, -1): total = total + i print "i = ", i, "\t total = ", total Tracing The First For Loop Example Execution >python for1.py Variables i total

Erroneous For Loop The logic of the loop is such that the end condition has been reached with the start condition. Example: for i in range (5, 0, 1): total = total + i print "i = ", i, "\t total = ", total Loop Increments Need Not Be Limited To One While i = 0 while (i <= 100): print "i =", i i = i + 5 For for i in range (0, 105, 5): print "i =", i

Sentinel Controlled Loops The stopping condition for the loop occurs when the sentinel value is reached. The complete program can be found in UNIX under: /home/courses/217/examples/loops/sumseries.py total = 0 temp = 0 while (temp >= 0): temp = input ("Enter a positive integer (negative to end series):") if (temp >= 0): total = total + temp print "Sum total of the series:", total Solving A Problem Using Loops Problem: Write a program that will execute a game: The program will randomly generate a number between one and ten. The player will be prompted to enter their guess. The program will continue the game until the player indicates that they no longer want to continue. The full program can be found in UNIX under: /home/courses/217/examples/loops/guessinggame.py

Guessing Game guess = 0 answer = 0 choice = "Y" while choice not in ("q", "Q"): answer = random.randrange (10) + 1 guess = input ("Enter your guess: ") if (guess == answer): print "You guessed correctly!" else: print "You guessed incorrectly" print "Number was", answer, ", your guess was", guess print "Play again? Enter 'q' to quit, anything else to play again" print "Choice:", choice = raw_input() print "" print "Exiting game" Recap: What Looping Constructs Are Available In Python/When To Use Them Construct Pre-test loops While For When To Use You want the stopping condition to be checked before the loop body is executed (typically used when you want a loop to execute zero or more times). The most powerful looping construct: you can write a while-do loop to mimic the behavior of any other type of loop. In general it should be used when you want a pre-test loop which can be used for most any arbitrary stopping condition e.g., execute the loop as long as the user doesn t enter a negative number. A counting loop : You want a simple loop to count up or down a certain number of times. Post-test: None in Python You want to execute the body of the loop before checking the stopping condition (typically used to ensure that the body of the loop will execute at least once). The logic can be simulated in Python however.

Infinite Loops Infinite loops never end (the stopping condition is never met). They can be caused by logical errors: The loop control is never updated (Example 1 below). The updating of the loop control never brings it closer to the stopping condition (Example 2 next slide). Example 1 (The full version can be found in UNIX under /home/courses/217/examples/loops/infinite1.py) i = 1 while (i <=10): print "i = ", i i = i + 1 To stop a program with an infinite loop in Unix simultaneously press the <ctrl> and the <c> keys Infinite Loops (2) Example 2 (The full version can be found in Unix under /home/courses/217/examples/loops/infinite2.py) while (i > 0): print "i = ", i i = i + 1 To stop a program with an infinite loop in Unix simultaneously press the <ctrl> and the <c> keys

Nested Loops One loop executes inside of another loop(s). Example structure: Outer loop (runs n times) Inner loop (runs m times) Body of inner loop (runs n x m times) Example program (the full program can be found in UNIX under: /home/courses/217/examples/loops/nested.py) for i in range (1, 3, 1): for j in range (1, 4, 1): print "i = ", i, " j = ", j Testing Loops Make sure that the loop executes the proper number of times. Test conditions: 1) Loop does not run 2) Loop runs exactly once 3) Loop runs exactly n times

Testing Loops: An Example sum = 0 i = 1 last = 0 last = input ("Enter the last number in the sequence to sum : ") while (i <= last): sum = sum + i print "i = ", i i = i + 1 print "sum =", sum You Should Now Know When and why are loops used in computer programs What is the difference between pre-test loops and post-test loops How to trace the execution of pre-test loops How to properly write the code for a loop in a program What are nested loops and how do you trace their execution How to test the execution of loop