5.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 dive into the 'for' loop. Can anyone tell me what a loop is in programming?
Isn't it a way to repeat a set of statements?
Exactly! Loops help us to execute code a specific number of times or for each item in a sequence. The 'for' loop is specifically for iterating over sequences like lists, strings, or ranges.
What does 'iterate' mean?
'Iterate' means to go through each item in a sequence one at a time. For example, if you have a list of numbers, a 'for' loop can help us access each number in turn. Let's look at the syntax.
The syntax is as follows: `for variable in sequence:` followed by the code block we want to execute. Remember, the 'variable' will take on each value in the 'sequence' during each iteration.
Can we see a code example?
"Sure! Here's a simple example:
Understanding the range() Function
🔒 Unlock Audio Lesson
Sign up and enroll to listen to this audio lesson
Now let's dig deeper into the range() function. Who can remind us what it does within a for loop?
It generates a sequence of numbers.
Correct! The function can be called in a few different ways: `range(n)` to get numbers from 0 to n-1, `range(start, stop)` to count from start to stop-1, or `range(start, stop, step)` to define how much to increment by each time. Could anyone give me an example?
What if we use `range(2, 10, 2)`?
"Great thought! This will give us even numbers from 2 to 8 if we loop through it. Like this:
Introduction & Overview
Read summaries of the section's main ideas at different levels of detail.
Quick Overview
Standard
In this section, you will learn how the 'for' loop functions in Python, particularly in looping through various sequences such as lists, strings, and ranges. You will also explore the usage of the 'range()' function to generate number sequences for iterations.
Detailed
The for Loop
The 'for' loop is a fundamental control structure in Python that facilitates the execution of a group of statements multiple times. It iterates over a specified sequence, allowing for easier management of repetitive tasks in code. In this section, the primary focus will be on:
- Syntax of the for Loop: The basic structure is as follows:
- Using the range() Function: The
range()function is widely utilized within 'for' loops to provide sequences of numbers. range(n): gives numbers from0ton-1.range(start, stop): generates numbers fromstarttostop-1.range(start, stop, step): increments numbers bystep.
The ability to iterate over various sequences, such as lists and strings, leads to concise code and less redundancy, ultimately making your code more efficient and maintainable.
Audio Book
Dive deep into the subject with an immersive audiobook experience.
Overview of the for Loop
Chapter 1 of 4
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
Used to iterate over sequences (like lists, strings, or ranges).
Detailed Explanation
The for loop is a control structure that allows you to run a block of code repeatedly for each item in a sequence. A sequence can be a list, string, or even a range of numbers. The loop automatically takes each item one after the other without needing to manually specify the iteration.
Examples & Analogies
Think of a for loop like a teacher going down a list of names to call students one by one to present their project. Instead of randomly picking students, the teacher sequentially checks off each name on the list.
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 sequence:
# code block
Detailed Explanation
The syntax starts with the keyword 'for', followed by a variable name that will represent each item in the sequence. The 'in' keyword indicates the sequence being iterated over, and the code block (indented under the loop) is what will be executed for each item. It’s important to ensure proper indentation, as this shows which code belongs to the loop.
Examples & Analogies
Imagine a recipe with steps. The 'for' is like saying 'for each ingredient in the recipe, do the following'. Each ingredient has specific instructions, and you carry them out in a precise order (indented steps) because each step relates directly to the ingredient being checked.
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(5):
print(i)
Output:
0
1
2
3
4
Detailed Explanation
In this example, 'range(5)' generates a sequence of numbers from 0 to 4. The for loop assigns each number to the variable 'i' and executes the print function, which displays the value of 'i'. This continues until all numbers in the range have been processed.
Examples & Analogies
Think of it like a countdown timer that goes from 4 to 0. Every second, the timer shows the next number down on the screen until it reaches zero. Just like the timer, the for loop counts through its list of numbers sequentially.
Understanding the range() Function
Chapter 4 of 4
🔒 Unlock Audio Chapter
Sign up and enroll to access the full audio experience
Chapter Content
🎯 range() Function
● range(n) – from 0 to n-1
● range(start, stop) – from start to stop-1
● range(start, stop, step) – increment by step
✅ Example:
for num in range(2, 10, 2):
print(num)
Detailed Explanation
The 'range()' function is a built-in Python function that generates a sequence of numbers. You can specify the starting point, the endpoint, and the step size. In the example, 'range(2, 10, 2)' starts at 2, stops before 10, and counts by increments of 2, which results in printing even numbers: 2, 4, 6, and 8.
Examples & Analogies
If you think about counting coins, consider that you only pick the even coins (2-cent, 4-cent, etc.) from the pile starting from 2 up to just before 10. You're selectively choosing the ones you want based on your specified criteria.
Key Concepts
-
For Loop: A loop constructs that iterates over sequences.
-
Sequence: Any ordered collection like lists or strings.
-
Range Function: Generates a sequence of numbers for iterations.
-
Iteration: The act of looping through items in a sequence.
Examples & Applications
Using for loop to print numbers from 0 to 4:
for i in range(5):
print(i)
Using for loop with the range function for even numbers:
for num in range(2, 10, 2):
print(num)
Memory Aids
Interactive tools to help you remember key concepts
Rhymes
In Python, the for loop does roam, over lists and ranges, it finds a home.
Stories
Imagine a robot that needs to count to five. With a for loop, it easily moves one by one from zero to five.
Memory Tools
To remember the for loop: F - Follows, O - Over, R - Ranges.
Acronyms
For
- For each
- Object
- Repeatedly.
Flash Cards
Glossary
- for Loop
A control structure for executing a block of code multiple times, iterating over a sequence.
- range() Function
A built-in Python function that generates a sequence of numbers, commonly used for iterations in loops.
- Iteration
The process of executing a block of code repeatedly, once for each item in a sequence.
- Sequence
An ordered collection of items, like lists, strings, or any range of numbers.
Reference links
Supplementary resources to enhance your learning experience.