Lesson 17. Customizing loops

 

After reading lesson 17, you’ll be able to

  • Write more-complicated for loops that start and end at custom values
  • Write loops that iterate over strings

You write programs so you can make the user’s life easier in some way, but that doesn’t mean that the programmer’s experience with writing a program should be tedious. Many programming languages have added customizations to certain language constructs so that a programmer can take advantage of them and write code more efficiently.

Consider this

You give your spouse a list of movies you want to watch over the course of one year. Every odd-numbered movie is action, and every even-numbered movie is comedy:

  • What pattern can you follow to reliably make sure you watch every comedy movie in the list?
  • What pattern can you follow to reliably make sure you watch every action movie in the list?

Answer:

  • Go through the list and watch every other movie, starting with the second in the list.
  • Go through the list and watch every other movie, starting with the first in the list.

17.1. Customizing loops

You can specify starting values, ending values, and step sizes when using the range keyword. range(start,end,step) takes at least one number and can take up to three numbers in its parentheses. The numbering rules are similar to indexing into strings:

17.2. Looping over strings

 
 
 
 

Summary

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage