lecture 20 while loops
play

Lecture 20: While Loops (Sections 7.3, 7.4) CS 1110 Introduction - PowerPoint PPT Presentation

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


  1. 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]

  2. 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

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

  4. Different types of Repetition 1. Process each item in a sequence for x in sequence: § Compute statistics for a dataset. process x § Send all your contacts an email. 2. Do something n times for x in range(n): do something § 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. ??? 4

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

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

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

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

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

  10. A2: What gets printed? a = 4 a = 0 while a > 0: while a < 3: a = a - 1 if a < 2: a = a + 1 print(a) print(a) ! 0 p o o l e t i n i f n I 10

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

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

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

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

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

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

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

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

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

  20. 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)): p e e k secret.word_so_far() n a c y l l a u t e s g U u o y user_guess = input("Guess a letter: ") l i t n u g n i g s s n e o u r g w secret.apply_guess(user_guess): r e b m u n e m o s if secret.is_solved(): print("YOU WIN!!!") break #jumps out of the for-loop secret.reveal() 20

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

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

Recommend


More recommend