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

Similar documents
Lecture 7: Functions. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Loops / Repetition Statements

Lecture 18: Lists II. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

Lecture 10: Boolean Expressions

Programming Training

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

Quiz Determine the output of the following program:

Lecture 4: Simple Input-Calculate-Output Programs

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

switch-case Statements

CS 241 Control Structures. Christopher A. Gantz. SPS Undergraduate Program Regis University

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Lecture 8: Simple Calculator Application

Simple Lexical Analyzer

Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:

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

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Lecture 15: Dictionaries

Arithmetic Compound Assignment Operators

Flow Control: Branches and loops

Algorithms and Data Structures

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

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

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

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

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

Introduction. C provides two styles of flow control:

Computer Programming I - Unit 5 Lecture page 1 of 14

LOOPS. Repetition using the while statement

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

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

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

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today.

Fundamentals of Programming. Week 1 - Lecture 3: Loops

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

CS1004: Intro to CS in Java, Spring 2005

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Why Is Repetition Needed?

Condition Controlled Loops. Introduction to Programming - Python

CS302: Self Check Quiz 2

Control structure: Repetition - Part 3

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

Condition Controlled Loops. Introduction to Programming - Python

Example: Monte Carlo Simulation 1

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

Lecture 8: Context Free Grammars

Syntax of for loop is as follows: for (inite; terme; updatee) { block of statements executed if terme is true;

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

UNIT 2B An Introduc0on to Programming (for loops) for Loop (simple version) for loop_variable in range(n): loop body

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

Repetition and Loop Statements Chapter 5

Chapter 4: Control structures. Repetition

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Looping. Arizona State University 1

Computer Programming

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

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

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

Repetition, Looping. While Loop

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

Conditionals and Recursion. Python Part 4

Principles of Computer Science I

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Lecture 2: Writing Your Own Class Definition

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Chapter 4: Control structures

Chapter 8 Statement-Level Control Structures

Lecture 20: While Loops (Sections 7.3, 7.4)

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

REPETITION CONTROL STRUCTURE LOGO

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

UNIT 2B An Introduction to Programming ( for -loops) Principles of Computing, Carnegie Mellon University

(Python) Chapter 3: Repetition

Lecture Notes, CSE 232, Fall 2014 Semester

Lecture 7 Tao Wang 1

Conditionals and Loops

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

Lecture 8. Conditionals & Control Flow

Control Structures 1 / 17

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

Controls Structure for Repetition

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

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

Structured Programming. Dr. Mohamed Khedr Lecture 9

ECE 122. Engineering Problem Solving with Java

1. What is the minimum number of bits needed to store a single piece of data representing: a. An integer between 0 and 100?

CS 112: Intro to Comp Prog

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

Lecture 2: Python Arithmetic

CS 106 Introduction to Computer Science I

Transcription:

Lecture 11: while loops CS1068+ Introductory Programming in Python Dr Kieran T. Herley Python s while loop. Summary Department of Computer Science University College Cork 2017-2018 KH (24/10/17) Lecture 11: while loops 2017-2018 1 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 2 / 1 for loop revisited while loop Syntax For loop is generally used where number of iterations (repetitions) is known in advance for i in range(n + 1): total = total + i What if we don t know this number? Components while condition : body Condition Boolean condition Loop body Indented block of statements Meaning Condition controls loop execution Repeatedly execute loop body but check that condition is True before each repetition; terminate loop if condition is False KH (24/10/17) Lecture 11: while loops 2017-2018 3 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 4 / 1

while loop cont d A concrete example while condition : body 1 Evaluate condition: if False skip to Step 4 otherwise proceed to Step 2 2 Execute loop body 3 Go back to Step 1 4 (Continue execution with statement following the while) Task Read in a series of positive numbers one per line and output their sum; series terminated by 1 (not part of series) e.g. Terminology Ideas 1 17 5 1 23 The 1 is known as a sentinel No predetermined indication of length of series Use while loop: condition captures have we reached the end of the series? KH (24/10/17) Lecture 11: while loops 2017-2018 5 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 6 / 1 Solution num = int(input( Please enter a number: )) while num!= 1: num = int(input( Please enter a number: )) print( Total is, total ) Solution cont d while num!= 1: num = int(input( Please...: )) print ( Total is, total ) Trace of program execution for series: 1 17 5 1 num =... (reads 1) num!= -1? (True) (now 1) num =... (read 17) num!= -1? (True) (now 18) num =... (reads 5) num!= -1? (True) (now 23) num =... (reads -1) KH (24/10/17) Lecture 11: while loops 2017-2018 7 / 1 num!= -1? (False) print Note: Loop execution interleaves condition check and execute body steps KH (24/10/17) Lecture 11: while loops 2017-2018 8 / 1

Solution cont d A variation on the theme while num!= 1: An alternative to the sentinel approach is the go-around option. Ask the user after each number whether it is the last print ( Total is, total ) KH (24/10/17) Lecture 11: while loops 2017-2018 9 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 10 / 1 Another solution Another solution cont d done = False while not done: num = int(input( Please enter a number: )) go again = input( Would you like another (y/n)? ) done = go again. strip ()!= y print( total was, total ) Statement done =... controls loop Variable done transmits it done = False while not done: go again = input( Would...? ) done = go again. strip ()!= y print ( total was, total ) Performs at least one iteration Execution sequence: Execute body Check if finished Execute body Check if finished Execute body Check if finished etc. Effectively check happens at the end of each loop body execution rather than the start KH (24/10/17) Lecture 11: while loops 2017-2018 11 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 12 / 1

for loops vs while loops Syracuse sequence Can always re-write for loops using while for n in range(20, 10, 2): total = total + n print( total ) n = 20 while n > 10: total = total + n n = n 2 print( total ) while is more powerful, but can be harder to work with General rule: Favour for loops for definite iteration i.e. where number of iterations known in advance and while loops otherwise The Syracuse sequence is generated by starting with a natural numbers and repeatedly applying the following function until 1 is reached: { x/2 if x even syr(x) = 3x + 1 if x odd Example (n = 5): 5, 16, 8, 4, 2, 1 Task: Write a program that generates the Syracuse sequence for a given value of n KH (24/10/17) Lecture 11: while loops 2017-2018 13 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 14 / 1 Syracuse function Generating Syracuse series def syr(x): if x % 2 == 0: return x // 2 else : return 3 x + 1 current = n print(current, :, end = ) while current!= 1: current = syr(current) print(current,, end = ) print() Wrap a for loop around this to generate series for values 1 to 20 say. KH (24/10/17) Lecture 11: while loops 2017-2018 15 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 16 / 1

Prime numbers Testing for primality A whole number is prime if it has no divisors other than itself and one Examples: primes 2, 3, 5, 7, 11, 13, (infinitely many) non primes 4, 10, 34 Task: Write a Python function that determines whether a given number is prime or not Idea: Try candidate divisors 2, 3, 4,, n 1 in turn to see if any divide number evenly; if none do then n is prime, otherwise not def is prime (n): # Return True if ' n' is prime no divisors = n > 1 cand = 2 while no divisors and cand < n: no divisors = no divisors and n % cand!= 0 cand = cand + 1 return no divisors KH (24/10/17) Lecture 11: while loops 2017-2018 17 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 18 / 1 Testing for primality cont d Goldbach s Conjecture def is prime (n): # Return True if n is prime no divisors = n > 1 cand = 2 while no divisors and cand < n: no divisors = no divisors \ and n % cand!= 0 cand = cand + 1 return no divisors Easy to see function produces correct answer for {0, 1, 2} Variable cand steps through values 2, 3, 4,, n 1 in turn If divisor found, variable no divisors set to False Once False, value can never revert to True The conjecture Every even integer greater than two can be expressed as the sum of two primes Believed to be true, but no known proof Task Verify the conjecture for integers up to 200 Idea For specific number n and value i, see if i and n i are both prime Try each possible i from 2 upwards, until you find a pair that works KH (24/10/17) Lecture 11: while loops 2017-2018 19 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 20 / 1

Back Material Solution Notes and Acknowledgements print(k, :, end = ) for i in range(2, k): if is prime ( i ) and is prime(k i): print(str( i ), +, str(k i), end = ) break print() Wrap a for loop around this to repeat this for even values of k in the range 4 to 200 (say) Reading Code Acknowledgements KH (24/10/17) Lecture 11: while loops 2017-2018 21 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 22 / 1