21.2 - The FOR Loop
Enroll to start learning
You’ve not yet enrolled in this course. Please enroll for free to listen to audio lessons, classroom podcasts and take practice test.
Interactive Audio Lesson
Listen to a student-teacher conversation explaining the topic in a relatable way.
Introduction to the FOR Loop
🔒 Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
Today, we are going to discuss an important programming construct: the FOR loop. Does anyone know why we might want to use a loop in programming?
I think it helps us run the same code multiple times without repeating it ourselves.
Exactly! The FOR loop allows us to execute a block of code a specified number of times—useful when we know how many iterations we want to complete. Let’s look at the syntax. Can anyone try to summarize it?
It starts with 'for', then a variable name, followed by 'in range', and the starting and stopping points.
Good job! Here’s a memory aid: remember 'FRS' for 'For, Range, Step' to help you recall the framework of the loop.
Can we see an example of that?
"Absolutely! Here’s a simple example:
Using the FOR Loop with Lists
🔒 Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
Now let’s discuss another application of the FOR loop: iterating over lists. How do you think a FOR loop could be used with a list of items?
Maybe to print each item in the list?
"Absolutely! Here is an example:
Key Points & Recap
🔒 Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
To wrap up our session on FOR loops, can someone remind me what key points we’ve covered today?
We learned that the FOR loop is used to repeat code a specific number of times.
And we also saw how to use it with ranges and lists.
Great summaries! Remember, using the FOR loop helps avoid repetitive code and saves time. Next time, we’ll dive into WHILE loops for tasks that require conditions instead of set iterations.
Introduction & Overview
Read summaries of the section's main ideas at different levels of detail.
Quick Overview
Standard
In this section, we explore the FOR loop, which facilitates the repetition of code a specific number of times using a defined syntax. We also discuss using FOR loops with range and lists, providing examples to illustrate the concept effectively.
Detailed
The FOR Loop
The FOR loop is a key component in programming that allows for a block of code to be executed multiple times. It is particularly useful when the number of iterations is known ahead of time. The basic syntax for a FOR loop is:
Components:
- start: The initial value (default is 0).
- stop: The loop runs until it reaches this value, not including it.
- step: The interval at which the loop increases (default is 1).
Example:
In the code example below, the FOR loop iterates from 1 to 5, printing out "Hello" followed by the current value of i:
Output:
Hello 1 Hello 2 Hello 3 Hello 4 Hello 5
Using FOR with Lists:
FOR loops are also effective for iterating through elements of lists. For example:
This outputs each color in the list:
red blue green
In summary, the FOR loop is an essential tool in programming that allows for efficient iteration over a sequence of numbers or items, enabling repetitive tasks to be handled elegantly.
Audio Book
Dive deep into the subject with an immersive audiobook experience.
What is the FOR Loop?
Chapter 1 of 4
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
The for loop is used to repeat a block of code a specific number of times. It is typically used when the number of iterations is known.
Detailed Explanation
The 'for loop' is a powerful programming structure that allows you to execute a set of instructions repeatedly for a fixed number of times. This is particularly useful when you know beforehand how many times you want to run a block of code. Instead of writing the same line of code multiple times, you can group it together in a loop which will automatically take care of the repetitions for you.
Examples & Analogies
Imagine you are baking cookies. If you want to bake 10 cookies and the process for each cookie is the same, you could describe the process once and use a timer to remind you each time to put a cookie in the oven. Similarly, the 'for loop' allows you to repeat a task without rewriting the code, just like following a single recipe for multiple cookies.
Syntax of the FOR Loop
Chapter 2 of 4
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
Syntax:
for variable in range(start, stop, step):
statement(s)
Detailed Explanation
The syntax of the 'for loop' indicates how to set up the loop's parameters. The structure starts with 'for', followed by a variable that will take on the value from the range. The 'range' function specifies three components: the start value (where the loop begins), the stop value (the endpoint, not including this value), and the step value (the increment by which the loop will proceed). This allows for versatile looping, where you can start counting from different points and at different intervals.
Examples & Analogies
Think of a phone number dialer. You need to enter digits one by one, starting from a specific number (like dialing from 1 to 10). You can choose to skip every second number (like dialing 2, 4, 6, etc.), just as with the 'for loop' you can decide the start, stop, and step for how you process each number.
Example of the FOR Loop
Chapter 3 of 4
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
Example:
for i in range(1, 6):
print("Hello", i)
Output:
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Detailed Explanation
In this example, the loop is set to run from 1 to 5. For each iteration of the loop, the variable 'i' takes on a new value from the range (1, 2, 3, 4, 5). Inside the loop, the print function is called, which displays 'Hello' followed by the current value of 'i'. This results in 'Hello 1', 'Hello 2', and so on, all the way to 'Hello 5'. This illustrates how easily a 'for loop' can produce repeated output.
Examples & Analogies
Imagine each time you greet someone by saying 'Hello' followed by their name. If you have a list of five friends, the 'for loop' allows you to automatically perform this greeting for each friend without having to type it out five distinct times.
Using FOR with Lists
Chapter 4 of 4
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
Using FOR with Lists:
colors = ['red', 'blue', 'green']
for color in colors:
print(color)
Detailed Explanation
In this segment, we see how the 'for loop' can be utilized to iterate over a list of items. Here, we define a list called 'colors' containing three color names. The loop iterates through each color in the list, and during each iteration, the 'color' variable takes on the value of the current item. The printed output will be each color in the list, one after the other. This demonstrates the flexibility of 'for loops' to work with collections such as lists.
Examples & Analogies
Consider a box of colored pencils. If you want to show each pencil to your friend one at a time, you can use the 'for loop' to pick each pencil, one after the other, without forgetting any color. Just as you stream a sequence of actions using the loop, you can present each color to your friend systematically.
Key Concepts
-
FOR Loop: A structure that allows repeated execution of code for a specified number of times.
-
Range Function: Used to define the start and stop points for iteration in a FOR loop.
-
Iteration: The act of executing the loop's code block multiple times.
Examples & Applications
Using a FOR loop to print numbers: for i in range(1, 5): print(i) outputs 1 to 4.
Iterating through a list of colors: colors = ['red', 'blue']; for color in colors: print(color) outputs 'red' and 'blue'.
Memory Aids
Interactive tools to help you remember key concepts
Rhymes
For loops go 'round, without a sound, run your code, from start to ground.
Stories
Imagine a chef using a FOR loop to gather ingredients. Each time they scoop flour, they count: one for the cake, two for the bread, three for the muffins, and so on until they're done!
Memory Tools
Remember 'FLS' for 'For, List, Sequence' to recall the key elements of a FOR loop.
Acronyms
FRS - For, Range, Step, to remember the key components of a FOR loop's function.
Flash Cards
Glossary
- FOR Loop
A control structure that repeats a block of code a specified number of times.
- Range
A function that generates a sequence of numbers, defined by a start, stop, and step.
- List
An ordered collection of items that can be iterated over in programming.
- Iteration
The process of executing a block of code multiple times.
Reference links
Supplementary resources to enhance your learning experience.