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:
- Create a file named for_loops.py in your part44 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: Loop Through a List
-
Task: Create a list
fruits = ['apple', 'banana', 'orange', 'grape', 'mango']. -
Goal: Write a for loop that prints each fruit on
its own line. Then modify the loop to print each fruit in uppercase
using the
.upper()method.
Exercise 2: Loop Through a String
-
Task: Create a variable
name = "Python". - Goal: Write a for loop that prints each character in the string on its own line. Then modify the loop to print the character and its position in the string using a counter variable that you increment manually on each iteration.
Exercise 3: Loop with a Condition
-
Task: Create a list
numbers = [4, 7, 2, 9, 1, 5, 8, 3, 6, 10]. - Goal: Write a for loop that prints only the numbers that are greater than 5. Write a comment explaining how the loop and the conditional statement work together.
Exercise 4: Nested Loop - Multiplication Table
-
Task: Create two lists
rows = [1, 2, 3, 4, 5]andcols = [1, 2, 3, 4, 5]. - Goal: Write a nested loop that prints a 5x5 multiplication table. Each line should print the result of the outer number multiplied by the inner number. Write a comment explaining how many total iterations the nested loop performs and why.
Exercise 5: Three Level Nest
-
Task: Create three lists:
departments = ['Engineering', 'Design'],roles = ['Junior', 'Senior'],locations = ['London', 'New York', 'Tokyo']. - Goal: Write a three level nested loop that prints every possible combination of department, role and location. Before running the code write a comment predicting how many lines will be printed. After running it write a comment confirming your prediction and explaining how you calculated the total number of iterations.
Don't Forget to commit and Push!