5 While-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming.

Slides:



Advertisements
Similar presentations
4 If-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming.
Advertisements

CS107 Introduction to Computer Science Lecture 3, 4 An Introduction to Algorithms: Loops.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.1 Chapter 5 Loops.
Introduction to Computing Science and Programming I
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Structured programming
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
INTRODUCTION TO PYTHON PART 3 - LOOPS AND CONDITIONAL LOGIC CSC482 Introduction to Text Analytics Thomas Tiahrt, MA, PhD.
Introduction to Computer Programming in c
Chapter 4: Looping CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp.
The break and continue statements. Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement)
Fundamentals of Python: From First Programs Through Data Structures
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Fundamentals of Python: First Programs
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
Python Control Flow statements There are three control flow statements in Python - if, for and while.
1 4.8The do/while Repetition Structure The do/while repetition structure –Similar to the while structure –Condition for repetition tested after the body.
1 Inference Rules and Proofs (Z); Program Specification and Verification Inference Rules and Proofs (Z); Program Specification and Verification.
CSI 3125, Axiomatic Semantics, page 1 Axiomatic semantics The assignment statement Statement composition The "if-then-else" statement The "while" statement.
Chapter 5 Control Structures: Loops 5.1 The while Loop The while loop is probably the most frequently used loop construct. The while loop is a conditional.
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Copyright © Cengage Learning. All rights reserved. CHAPTER 4 ELEMENTARY NUMBER THEORY AND METHODS OF PROOF.
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
Data Structures Chapter 1- Introduction Mohamed Mustaq.A.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
1 Flow of control Sequential Executing instructions one by one, in exact order given Selection Choosing to execute a particular set of statements depending.
8 For-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1.
Lecture 4: Calculating by Iterating. The while Repetition Statement Repetition structure Programmer specifies an action to be repeated while some condition.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Counter-Controlled Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
1 Introduction  Algorithms  Data structures  Abstract data types  Programming with lists and sets © 2008 David A Watt, University of Glasgow Algorithms.
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.
Algorithm Discovery and Design Objectives: Interpret pseudocode Write pseudocode, using the three types of operations: * sequential (steps in order written)
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
3 Basics © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
ITERATION. Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Application: Algorithms Lecture 19 Section 3.8 Tue, Feb 20, 2007.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming 1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Control Flow (Python) Dr. José M. Reyes Álamo. 2 Control Flow Sequential statements Decision statements Repetition statements (loops)
Control Structures: Examples. for-loop example Q: If a=1, b=3, and x=7, what is the value of x when the loop terminates? A: x=1 for(k=a; k
PH2150 Scientific Computing Skills Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances.
Introduction to Computer Programming
CSE 220 – C Programming Loops.
ECE Application Programming
REPETITION CONTROL STRUCTURE
Lecture 7: Repeating a Known Number of Times
Python: Control Structures
© 2010 David A Watt, University of Glasgow
CS1371 Introduction to Computing for Engineers
Ch 7: JavaScript Control Statements I.
2008/09/24: Lecture 6b CMSC 104, Section 0101 John Y. Park
Repetition and Loop Statements
Axiomatic semantics Points to discuss: The assignment statement
Loops (iterations, repetitions)
Chapter 5 Loops.
Application: Algorithms
Application: Algorithms
Another Example Problem
EECE.2160 ECE Application Programming
COMPUTING.
Presentation transcript:

5 While-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming

5-2 While-statements  A while-statement is a loop that enables a program to execute code repeatedly.  The while-statement has the form: while expression : body a sequence of statements (the loop body)  To execute this while-statement: 1. Evaluate expression to either True or False. 2. If the result was True, execute body and then repeat from step 1 3. If the result was False, exit the loop.

5-3 Example: computing a square root (1)  Newton’s iterative algorithm to compute the square root of x: –Choose an initial estimate by setting r = 1.0 (say). –If r 2 is not approximately equal to x, improve the estimate by setting r = ½(r + x/r), and repeat. –If r 2 is approximately equal to x, the answer is r.  Let us take “r 2 is approximately equal to x” to mean that the relative difference between r 2 and x is less than 10 –4.

5-4 Example: computing a square root (2)  This function uses Newton’s algorithm: def square_root (x): # Return the square root of the positive number x. r = 1.0 while abs(x/r**2 – 1) > : r = 0.5 * (r + x/r) return r

5-5 Example: computing a GCD (1)  Euclid’s iterative algorithm to compute the greatest common divisor of positive integers m and n: –Set p = m and q = n. –If p is not a multiple of q, note the remainder, set p = q, set q = remainder, and repeat. –If p is a multiple of q, the answer is q.

5-6 Example: computing a GCD (2)  This function uses Euclid’s algorithm: def gcd (m, n): # Return the greatest common divisor of m and n. p = m q = n r = p % q while r != 0: p = q q = r r = p % q return q

5-7 Example: command-line program (1)  Requirements: –The program must accept a sequence of commands, each entered by the user in response to a suitable prompt. –The program must act on the valid commands “duck” and “dive”. –The program must reject any invalid command. –The program must terminate on the empty command “”.

5-8 Example: command-line program (2)  Possible output and input: Command? dive … Command? duck … Command? dunk - invalid command! Command? dive … Command? - terminated. output from the “dive” command output from the “duck” command

5-9 Example: command-line program (3)  Outline of the command-line program: done = False while not done: com = raw_input('Command? ') if com == 'duck': duck() elif com == 'dive': dive() elif com: print '- invalid command!' else: print '- terminated.' done = True

5-10 Example: printing a table (1)  Suppose that we want a program to tabulate GCDs, e.g.: Table of GCDs

5-11 Example: printing a table (2)  Tabulation program: def tabulate (low, high): # Tabulate the GCD of every pair of integers in the # range low … high. print_heading(low, high) m = low while m <= high: print_row (m, low, high) m += 1

5-12 Example: printing a table (3)  Tabulation program (continued): def print_heading (low, high): # Print column headings in the range low … high. print 'Table of GCDs' print '\t', n = low while n <= high: print n, '\t', n += 1 print prints a tab character, not followed by a line break prints a blank line

5-13 Example: printing a table (4)  Tabulation program (continued): def print_row (m, low, high): # Print a row of GCDs of m and integers in the # range low … high. print m, '\t', n = low while n <= high: print gcd(m, n), '\t', n += 1

5-14 Invariants  An invariant is a proposition that is always true at a particular point in a program or algorithm.  An invariant may be expressed in formal logic, in precise English, or by other means.  E.g.: if n > 0: m = n m = 2*m … n > 0 n > 0 and m > 0 n > 0 and m > 0 and m is even

5-15 Designing loops (1)  Schematic for a while-loop: loop prelude while loop condition : loop body loop postlude  The loop prelude consists of statements that prepare for the loop (e.g., by initialising variables).  The loop postlude consists of statements that use the result(s) of the loop.

5-16 Designing loops (2)  Formulate a loop invariant. This is an invariant that will be true before and after every iteration of the loop body.  The loop prelude must ensure that the loop invariant is initially true.  At the start of the loop body, both the loop invariant and the loop condition will be true. The loop body must ensure that the loop invariant is true at the end.  At the start of the loop postlude, the loop invaria- nt will be true but the loop condition will be false. even if it is temporarily false in the middle

5-17 Example: factorial function (1)  Outline of a factorial function: def fac (n): … return f f = n!  The code “…” must ensure that f = n!. But how?  Idea: successively compute 1!, 2!, 3!,..., n!.

5-18 Example: factorial function (2)  Introduce a loop in which p = 1, 2, 3,..., n. The loop invariant will be f = p!: def fac (n): p = 1 … while p != n: p = p+1 … return f f = p!f = p! and p ≠ nf = p!f = p! and p = n  Note that f = p! and p = n implies f = n!.

5-19 Example: factorial function (3)  The loop prelude sets p = 1. To establish the loop invariant f = p!, set f = 1: def fac (n): p = 1 f = 1 while p != n: p = p+1 … return f f = p! f = p! and p ≠ n f = p! f = p! and p = n

5-20 Example: factorial function (4)  The loop body increments p by 1. To re-establish the loop invariant f = p!, multiply f by p: def fac (n): p = 1 f = 1 while p != n: p = p+1 f = f*p return f f = p! f = p! and p ≠ n f = p! f = p! and p = n since p! = p × (p –1)!