Introduction

Published

2023-07-31

In this chapter, we introduce loops. With loops, we can automate repetitive tasks or calculations. Why are they called loops? Well, so far we’ve seen code which (apart from function calls) progresses in a linear fashion from beginning to end (even if there are branches, we still proceed in a linear fashion). Loops change the shape of the execution of our code in a very interesting and powerful way. They loop!

Looping allows portions of our code to execute repeatedly—either for a fixed number of times or while some condition holds—before moving on to execute the rest of our code.

Python provides us with two types of loop: for loops and while loops. for loops work by iterating over some iterable object, be it a list, a tuple, a range, or even a string. while loops continue as long as some condition is true.

Figure 1

With variables, functions, branching, and loops, we have all the tools we need to create powerful programs. All the rest, as they say, is gravy.

Learning objectives

  • You will learn how to use for loops and while loops.
  • You will learn how to iterate over sequences.
  • You will learn how to define and use conditions which govern a while loop.
  • You will learn how to choose which type of loop is best for a particular problem.

Terms, Python keywords, built-in functions, and types introduced

  • accumulator
  • alternating sum
  • arithmetic sequence
  • break
  • enumerate() (built-in) and enumerate (type)
  • Fibonacci sequence
  • for
  • iterable
  • iterate
  • loop
  • nested loop
  • range() (built-in) and range (type)
  • stride
  • summation
  • while

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).