Lesson 18. Repeating tasks while conditions hold

 

After reading lesson 18, you’ll be able to

  • Understand the syntax of another way to write a loop in a program
  • Repeat actions while a certain condition is true
  • Exit out of loops early
  • Skip statements in a loop

In the previous lessons, you assumed that you knew the number of times you wanted to repeat a block of code. But suppose, for example, that you’re playing a game with your friend. Your friend is trying to guess a number that you have in mind. Do you know in advance how many times your friend will guess? Not really. You want to keep asking them to try again until they get it right. In this game, you don’t know how many times you want to repeat the task. Because you don’t know, you can’t use a for loop. Python has another type of loop that’s useful in these kinds of situations: a while loop.

Consider this

Using only the information given in the following scenarios, do you know the maximum number of times you want to repeat the task?

  • You have five TV channels and you cycle though using the Up button until you’ve checked out what’s on every channel.
  • Eat a cookie until there are no more cookies in the box.
  • Say “punch buggy” every time you see a VW Beetle.
  • Click Next on your jogging song playlist until you’ve sampled 20 songs.

Answer:

  • Yes
  • Yes
  • No
  • Yes

18.1. Looping while a condition is true

If you have a task that must be repeated an uncertain number of times, a for loop won’t be appropriate because it won’t work.

18.2. Using for loops vs. while loops

 
 
 
 

18.3. Manipulating loops

 
 
 
 

Summary

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage