Flat_Eric Contemplating Data Type Conversions

For Loops

For Loops

Up to this point we have learned how to make our code smarter using logical operators and conditional statements. These tools allowed us to skip lines of code, check conditions, and make decisions. But we have still been limited to running each line of code only once.

Loops change everything. A loop allows you to run the same block of code over and over as many times as you need. This is where programming becomes truly powerful. Think about what a machine does best, it does not get tired, it does not lose focus, and it does not make mistakes from repetition. A computer can repeat the exact same task a million times in a fraction of a second with perfect accuracy every single time.

Before loops, if you wanted to print the numbers 1 to 100 you would have to write 100 individual print statements. With a loop you can do it in two lines. Before loops, if you wanted to check every item in a list you would have to write a separate check for each one. With a loop you write it once and Python handles the rest.

This is the true power of machines. Repetition at scale and at speed. Loops are one of the most important tools in all of programming and once you understand them your ability to write useful, real world code will grow dramatically.

For Loop Syntax

A for loop has two parts. The variable and the iterable. An iterable is anything that Python can step through one item at a time. The loop runs once for every item in the iterable, and each time it runs the variable holds the current item.

The structure looks like this:

for variable in iterable:

Read it in plain English. "For each item in this collection, do something." Just like if statements, the loop ends with a colon and the code block must be indented.

The variable name is completely up to you. By convention we usually name it something that describes a single item from the collection. For example if you are looping through a list of students you might call the variable student. If you are looping through a list of numbers you might call it num. Python does not care what you call it but a descriptive name makes your code much easier to read.

Looping Through a String

A string is iterable. Python will step through each character one at a time. Try it below and then change the string to see the result.

Looping Through a List

A list is the most common thing you will loop through. Python steps through each item in order from first to last.

Looping Through a Tuple

A tuple works exactly the same as a list in a for loop. The only difference is that a tuple is immutable, meaning you cannot change its contents while looping through it.

Looping Through a Set

A set is also iterable but remember that sets are unordered. Every time you loop through a set the order of the items may be different. Run the example a few times and observe the output.

Nested Loops

A nested loop is a loop inside another loop. For every single iteration of the outer loop, the inner loop runs completely from start to finish. This is an important concept to understand clearly before moving on.

Think of it like a clock. The minute hand completes a full rotation for every single tick of the hour hand. The inner loop is the minute hand, the outer loop is the hour hand.

The structure looks like this:

for outer in outer_iterable:
    for inner in inner_iterable:
        print(outer, inner)

Notice the indentation. The inner loop is indented inside the outer loop, and the print statement is indented inside the inner loop. Each level of nesting requires another level of indentation. Getting this wrong is one of the most common mistakes beginners make with nested loops.

Two Nested Loops

In this example we loop through two lists at the same time. For every item in the outer loop, Python runs through every item in the inner loop. Watch how many lines are printed and think about why.

Three Nested Loops

Adding a third loop increases the number of iterations dramatically. For every item in the outer loop, the middle loop runs completely. For every item in the middle loop, the inner loop runs completely. Try to predict how many lines will be printed before you run it.

With two lists of 3 items each, a double nested loop prints 9 lines. Adding a third list of 3 items produces 27 lines. The total number of iterations is always the product of the lengths of all the lists. This is why deeply nested loops can become very slow very quickly with large amounts of data.

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: Loop Through a List

Exercise 2: Loop Through a String

Exercise 3: Loop with a Condition

Exercise 4: Nested Loop - Multiplication Table

Exercise 5: Three Level Nest

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course