Introduction
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.
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 andwhile
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) andenumerate
(type)- Fibonacci sequence
for
- iterable
- iterate
- loop
- nested loop
range()
(built-in) andrange
(type)- stride
- summation
while
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.