Loops

Published

2023-07-31

Loops: an introduction

It is very often the case that we want to perform a repetitive task, or perform some calculation that involves a repetition of a step or steps. This is where computers really shine. Humans don’t much enjoy repetitive tasks. Computers couldn’t care less. They’re capable of performing repetitive tasks with relative ease.

We perform repetitive tasks or calculations, or operations on elements in some data structure using loops or iteration.

We have two basic types of loops in Python: while loops, and for loops.

If you’ve written code in another language, you may find that Python handles while loops in a similar fashion, but Python handles for loops rather differently.

A while loop performs some repetitive task or calculation as long as some condition is true.

A for loop iterates over an iterable. What is an iterable? An iterable is a composite object (made of parts, called “members” or “elements”) which is capable of returning its members one at a time, in a specific sequence. Recall: lists, tuples, and strings are all iterable.

Take, for example, this list:

m = [4, 2, 0, 1, 7, 9, 8, 3]

If we ask Python to iterate over this list, the list object itself “knows” how to return a single member at a time: 4, then 2, then 0, then 1, etc. We can use this to govern how many iterations we wish to perform and also to provide data that we can use in our tasks or calculations.

In the following sections, we’ll give a thorough treatment of both kinds of loop: while and for.

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