The FOR Loop - 21.2 | 21. IF, FOR, WHILE | CBSE Class 9 AI (Artificial Intelligence)
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skills—perfect for learners of all ages.

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Introduction to the FOR Loop

Unlock Audio Lesson

0:00
Teacher
Teacher

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?

Student 1
Student 1

I think it helps us run the same code multiple times without repeating it ourselves.

Teacher
Teacher

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?

Student 2
Student 2

It starts with 'for', then a variable name, followed by 'in range', and the starting and stopping points.

Teacher
Teacher

Good job! Here’s a memory aid: remember 'FRS' for 'For, Range, Step' to help you recall the framework of the loop.

Student 3
Student 3

Can we see an example of that?

Teacher
Teacher

"Absolutely! Here’s a simple example:

Using the FOR Loop with Lists

Unlock Audio Lesson

0:00
Teacher
Teacher

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?

Student 1
Student 1

Maybe to print each item in the list?

Teacher
Teacher

"Absolutely! Here is an example:

Key Points & Recap

Unlock Audio Lesson

0:00
Teacher
Teacher

To wrap up our session on FOR loops, can someone remind me what key points we’ve covered today?

Student 3
Student 3

We learned that the FOR loop is used to repeat code a specific number of times.

Student 4
Student 4

And we also saw how to use it with ranges and lists.

Teacher
Teacher

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 a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.

Quick Overview

The FOR loop is a programming construct that allows for the repetition of a block of code a specified number of times, making it essential for tasks where the number of iterations is known.

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:

Code Editor - python

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:

Code Editor - python

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:

Code Editor - python

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?

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

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

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

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

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

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

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

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.

Definitions & Key Concepts

Learn essential terms and foundational ideas that form the basis of the topic.

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 & Real-Life Applications

See how the concepts apply in real-world scenarios to understand their practical implications.

Examples

  • 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

Use mnemonics, acronyms, or visual cues to help remember key information more easily.

🎵 Rhymes Time

  • For loops go 'round, without a sound, run your code, from start to ground.

📖 Fascinating 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!

🧠 Other Memory Gems

  • Remember 'FLS' for 'For, List, Sequence' to recall the key elements of a FOR loop.

🎯 Super Acronyms

FRS - For, Range, Step, to remember the key components of a FOR loop's function.

Flash Cards

Review key concepts with flashcards.

Glossary of Terms

Review the Definitions for terms.

  • Term: FOR Loop

    Definition:

    A control structure that repeats a block of code a specified number of times.

  • Term: Range

    Definition:

    A function that generates a sequence of numbers, defined by a start, stop, and step.

  • Term: List

    Definition:

    An ordered collection of items that can be iterated over in programming.

  • Term: Iteration

    Definition:

    The process of executing a block of code multiple times.