Loops – For-loop Examples in Python

A for-loop is used when a sequence of statements is to be executed a known number of times. A for loop is controlled by an iterable expression like an expression using the range function.

We start – in Example 1 – with a brief explanation on why we need loops. Students typically don’t need much convincing that loops are needed to write efficient code. Examples 2 and 3 show two simple for-loop constructs. Examples 4 and 5 discuss more interesting problems, each using a for loop.

Example 1: Why do we need loops? (with video)

Example 2: Given two strings, find all characters appearing in both. 

Example 3: Print all the integers from 1 to 1000 that are multiples of both 6 and 10. 

Example 4: Better deal? (with video)

Example 5: Palindromes