Lecture 20: While Loops (Sections 7.3, 7.4)

Similar documents
isinstance and While Loops

Lecture 22. While Loops

Lecture 18: Using Classes Effectively (Chapter 16)

CS 1110: Introduction to Computing Using Python Loop Invariants

Lecture 24: Loop Invariants

CS Lecture 19: Loop invariants

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

Lecture 19: Subclasses & Inheritance (Chapter 18)

Lecture 13. For-Loops

Lecture 11: Iteration and For-Loops

Iteration and For Loops

Lecture 13. For-Loops

Conditionals & Control Flow

CS 1110: Introduction to Computing Using Python Lists and Sequences

Fundamentals of Programming. Week 1 - Lecture 3: Loops

Lecture 2: Variables & Assignments

Lecture 8: Conditionals & Control Flow (Sections ) CS 1110 Introduction to Computing Using Python

Lecture 6: Specifications & Testing

LOOPS. Repetition using the while statement

Lecture 10. Daily Puzzle

Lecture 10: Lists and Sequences

Lecture 17: Classes (Chapter 15)

CS1110. Lecture 6: Function calls

Lecture 4: Defining Functions (Ch ) CS 1110 Introduction to Computing Using Python

CS1 Lecture 12 Feb. 11, 2019

CS 1110, LAB 3: STRINGS; TESTING

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

Condition Controlled Loops. Introduction to Programming - Python

CS 1110, LAB 10: ASSERTIONS AND WHILE-LOOPS 1. Preliminaries

Repetition Structures

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

Lecture 4: Defining Functions

CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS First Name: Last Name: NetID:

Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python

Lecture 7: Objects (Chapter 15) CS 1110 Introduction to Computing Using Python

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

CMSC201 Computer Science I for Majors

(Python) Chapter 3: Repetition

Lecture 9: Memory in Python

Lecture 3: Functions & Modules

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Lecture 17: Classes (Chapter 15)

21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

CS1 Recitation. Week 2

Programming for Experimental Research. Flow Control

CS Lecture 25: Models, Views, Controllers, and Games. Announcements

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

CMPT 120 Introduction To Computing Science And Programming I. Pseudocode. Summer 2012 Instructor: Hassan Khosravi

Algorithmic Thinking: Loops and Conditionals

CMSC201 Computer Science I for Majors

ASYMPTOTIC COMPLEXITY

CMSC201 Computer Science I for Majors

Programming in Python

6.189 Project 1. Readings. What to hand in. Project 1: The Game of Hangman. Get caught up on all the readings from this week!

CpSc 1111 Lab 4 Formatting and Flow Control

CS Lecture 18: Card Tricks. Announcements. Slides by D. Gries, L. Lee, S. Marschner, W. White

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming

Lecture 15. For-Loops

Lecture 9. Memory and Call Stacks

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

1 Lecture 5: Advanced Data Structures

DM536 Introduction to Programming. Peter Schneider-Kamp.

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

CS Prelim 1 Review Fall 2013

Lecture Transcript While and Do While Statements in C++

cs1114 REVIEW of details test closed laptop period

CS 221 Lecture. Tuesday, 11 October 2011

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

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

Genome Sciences 373 Genome Informa1cs. Quiz Sec1on #1 March 31, 2015

CS 1110, LAB 12: SEQUENCE ALGORITHMS First Name: Last Name: NetID:

DECISION CONTROL AND LOOPING STATEMENTS

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points

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

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

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

Introduction. C provides two styles of flow control:

Physics 2660: Fundamentals of Scientific Computing. Lecture 5 Instructor: Prof. Chris Neu

CS 1301 CS1 with Robots Summer 2007 Exam 1

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

npm run pull npm start

ISE 101 Introduction to Information Systems. Lecture 3 Objectives: While loops Strings

Lecture 13. Call Stacks & Debugging

VSCode: Open Project -> View Terminal -> npm run pull -> npm start. while Loops. Lecture 09. Don t Stop Til You Get Enough

Lecture 12. Lists (& Sequences)

CS1110. Lecture 6: Function calls

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

(Refer Slide Time: 00:26)

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

Lecture 5: Strings

APCS-AB: Java. Recursion in Java December 12, week14 1

CS Lecture 26: Subclasses in Event-driven Programs A7 is out! Get started right away you need time to ask questions.

CS Lecture 26: Grab Bag. Announcements

CS61A Lecture 36. Soumya Basu UC Berkeley April 15, 2013

CMSC 201 Spring 2018 Project 2 Battleship

Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

CS100 Spring 2017 Final

Transcription:

http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 20: While Loops (Sections 7.3, 7.4) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]

Announcements A3 is being graded this week A4 is out. Due next Thursday. Prelim 2 Tuesday, April 24 th, 7:30-9:00pm Please go to the same room you went for Prelim 1 Conflict assignment on CMS, due 11:59pm Tonight 2

Recall: For Loops for x in grades: print(x) loop sequence: grades loop variable: x body: print(x) To execute the for-loop: 1. Check if there is a next element of loop sequence grades has more elements True put next element in x 2. If so: assign next sequence element to loop variable False print(x) Execute all of the body Go back to Line 1 3. If not, terminate execution 3

Different types of Repetition 1. Process each item in a sequence Compute statistics for a dataset. Send all your contacts an email. 2. Do something n times Draw a checkers board. Run a protein-folding simulation for 10 6 time steps. 3. Do something an unknown number of times Fly up until you re near the ceiling. Play hangman until 6 strikes. for x in sequence: process x for x in range(n): do something??? 4

Beyond Sequences: The while-loop while <condition>: False statement 1 statement n condition True body body Relationship to for-loop Broader notion of keep working until done Must explicitly ensure condition becomes false You explicitly manage what changes per iteration 5

While-Loops and Flow import random num = random.randint(0,10) guessed_it = False print( I m thinking of a number. ) while not guessed_it: guess = int(input( Guess it: )) guessed_it = (num == guess) print( Well done!') I m thinking of a number. Guess it: 6 Guess it: 2 Guess it: 1 Guess it: 4 Well done! 6

Q1: What gets printed? a = 0 while a < 1: a = a + 1 a = 0 while a < 2: a = a + 1 a = 0 while a > 2: a = a + 1 7

A1: What gets printed? a = 0 while a < 1: a = a + 1 a = 0 while a < 2: a = a + 1 a = 0 while a > 2: a = a + 1 1 2 0 8

Q2: What gets printed? a = 4 while a > 0: a = a - 1 a = 0 while a < 3: if a < 2: a = a + 1 9

A2: What gets printed? a = 4 while a > 0: a = a - 1 a = 0 while a < 3: if a < 2: a = a + 1 0 Infinite loop! 10

Q3: What gets printed? a = 8 b = 12 while a!= b: if a > b: a = a - b else: b = b - a A: Infinite Loop! B: 8 C: 12 D: 4 E: I don t know 11

A3: What gets printed? a = 8 b = 12 while a!= b: if a > b: a = a - b else: b = b - a A: Infinite Loop! B: 8 C: 12 D: 4 E: I don t know CORRECT This is Euclid s Algorithm for finding the greatest common factor of two positive integers. Trivia: It is one of the oldest recorded algorithms (~300 B.C.) 12

for vs. while You can almost always use either Sometimes for is better Sometimes while is better 13

for vs. while do something n times for k in range(n): # do something k = 0 while k < n: # do something k = k+1 Must remember to increment My preference? for-loop 14

for vs. while do something an unknown number of times?? for k in range(big_num): # do something if time to stop: break while not time to stop: # do something My preference? while-loop 15

for vs. while do something to each element of a sequence for k in range(len(seq)): seq[k] = seq[k]+1 k = 0 while k < len(seq): seq[k] = seq[k]+1 k = k+1 while is more flexible, but often requires more code My preference? for-loop 16

for vs. while do something until a limit is reached make a table of squares up to N seq = [] n = math.floor(sqrt(n)) + 1 for k in range(n): seq.append(k*k) for-loop requires you to know how many iterations you want ahead of time seq = [] k = 0 while k*k < N: seq.append(k*k) k = k+1 can use complex expressions to check if a task is done My preference? while-loop 17

for vs. while change a sequence s length remove all 3 s for list nums for i in list(range(len(nums))): if nums[i] == 3: del num[i] IndexError: list index out of range while 3 in nums: nums.remove(3) is this not beautiful? My preference? while-loop 18

for vs. while Fibonacci numbers: F 0 = 1 F 1 = 1 F n = F n 1 + F n 2 find 1 st n Fibonacci numbers fib = [1, 1] for k in range(2,n): fib.append(fib[-1] + fib[-2]) fib = [1, 1] while len(fib) < n: fib.append(fib[-1] + fib[-2]) loop variable not always used loop variable not always needed at all My preference? while-loop 19

Remember Hangman? import random, hangman word_list = [ words we want user to guess.. ] N_GUESSES = 10 secret = hangman.secretword(random.choice(word_list)) for n in list(range(n_guesses)): secret.word_so_far() user_guess = input("guess a letter: ") secret.apply_guess(user_guess): if secret.is_solved(): print("you WIN!!!") break #jumps out of the for-loop Usually can keep guessing until you get some number wrong secret.reveal() 20

Improving Hangman with while import random, hangman word_list = [ words we want user to guess.. ] N_GUESSES = 10 secret = hangman.secretword(random.choice(word_list)) n_strikes = 0 for n in list(range(n_guesses)): bad_guess = secret.word_so_far() user_guess = input("guess a letter: ") secret.apply_guess(user_guess) if secret.is_solved(): print("you WIN!!!") MAX_STRIKES = 10 break #jumps out of the loop while n_strikes < MAX_STRIKES: if bad_guess: n_strikes = n_strikes + 1 secret.reveal() 21

Using while-loops Instead of for-loops Advantages Better for modifying data More natural than range Works better with deletion Better for convergent tasks Loop until calculation done Exact steps are unknown Easier to stop early Just set loop var to False Disadvantages Infinite loops more likely Easy to forget loop vars Or get stop condition wrong Require more management Initialize the condition? Update the condition? 22