For Loop

Also known as: for, count-controlled loop

definition

A control structure that repeats a block of code a specific number of times or for each item in a collection. For loops are the most common loop type.

๐Ÿ’ก Intuition

A for loop is like 'do this for each...' โ€” for each student in the class, print their name. For each number from 1 to 10, add it to the total.

Core Idea

For loops are best when you know how many times to repeat or when iterating over a collection. The loop variable takes each value automatically.

๐Ÿ”ฌ Example

FOR i IN range(5): PRINT i prints 0, 1, 2, 3, 4. FOR name IN ['Alice', 'Bob']: PRINT 'Hello ' + name.

๐ŸŽฏ Why It Matters

For loops are the most common loop type. Processing lists, arrays, and ranges almost always uses a for loop.

โš ๏ธ Common Confusion

range(5) gives 0 to 4, not 1 to 5. Off-by-one errors are the most common for-loop bug.

Related Concepts

Prerequisites

Next Steps

How For Loop Connects to Other Ideas

To understand for loop, you should first be comfortable with iteration and while loop. Once you have a solid grasp of for loop, you can move on to array.

Go Deeper

Frequently Asked Questions

What is For Loop in CS Thinking?

A control structure that repeats a block of code a specific number of times or for each item in a collection.

Why is For Loop important?

For loops are the most common loop type. Processing lists, arrays, and ranges almost always uses a for loop.

What do students usually get wrong about For Loop?

range(5) gives 0 to 4, not 1 to 5. Off-by-one errors are the most common for-loop bug.

What should I learn before For Loop?

Before studying For Loop, you should understand: iteration, while loop.