The Python for Loop
The for loop in Python is a fundamental control structure used for definite iteration. This means you use it when you want to repeat a block of code a specific number of times, typically by iterating over a sequence like a list, tuple, string, or a range of numbers.
Think of it as a way to say: “For each item in this collection, take this specific action.”
Basic Syntax
The syntax of a for loop is clean and reads like plain English:
for variable_name in iterable:
# Code block to be executed for each item
# This block is indentedfor: The keyword that starts the loop.variable_name: A temporary variable that holds the current item from the iterable in each iteration. You can name it anything you like (for example:item,num,char).in: The keyword that connects the variable to the collection.iterable: An object that can be looped over, such as a list, string, tuple, dictionary, or arangeobject.:: The colon that marks the end of the loop declaration.- Indented Block: The code to be executed in each iteration. Indentation (usually 4 spaces) is how Python knows this code belongs to the loop.
Iterating Over Different Sequences
The for loop is incredibly versatile. Let us see how it works with different types of data:
The range() Function: Your Best Friend for Loops
Often, you do not have a sequence to loop over, but you want to repeat an action a certain number of times. The range() function is perfect for this. It generates a sequence of numbers on the fly.
Syntax of range()
The range() function can take one, two, or three arguments:
range(stop): Generates numbers starting at0up to (but not including)stop.range(start, stop): Generates numbers starting atstartup to (but not including)stop.range(start, stop, step): Generates numbers starting atstartup tostop, incrementing bystepeach time.
Examples with range()
Example 1: Simple Repetition
To run a block of code exactly 5 times, you can use range(5):
Example
Output:
The variable name i is a common convention for the loop counter, short for “index.”
Example 2: Custom Start and Stop
To generate numbers from 1 to 10 (inclusive), you need range(1, 11):
Example
Output:
Example 3: Using a Step
To print only the even numbers from 2 to 10, you can use a step of 2:
Example
Output:
Example 4: Counting Downwards
To count backwards, you need a negative step:
Example
Output:
Nested for Loops
You can put one for loop inside another. This is called a nested loop. It is useful for working with multi-dimensional data structures (like a grid or matrix) or for creating combinations.
The inner loop will complete all its iterations for every single iteration of the outer loop.
Example: Generating a Multiplication Table
Let us generate a multiplication table for numbers 1 through 3 using nested loops:
Example
Output:
Be careful with nested loops! If the outer loop runs N times and the inner loop runs M times, the code inside the inner loop will execute N * M times. This can make your programs slow if N and M are very large.
The for-else Clause
This is a lesser-known but incredibly useful feature of Python. The else block in a for loop is executed only if the loop completes all its iterations without hitting a break statement.
It is perfect for code that needs to run only when a search or process finishes “naturally.”
Example: Searching for an Item in a List
Let us try searching for a number that does not exist in our list:
Example
Output:
Now, let us try a case where the search number is successfully found:
Example
Output:
Practice Problems
Problem 1: Sum of Numbers
Write a program to calculate the sum of all numbers from 1 to 100:
PygroundTry It Out
Calculate the sum of all numbers from 1 to 100.
Expected Output:
The sum of numbers from 1 to 100 is: 5050
Output:
Problem 2: Count Vowels in a String
Write a program that counts the number of vowels (a, e, i, o, u) in a given string:
PygroundTry It Out
Count the number of vowels in the string 'hello world'.
Expected Output:
The number of vowels is: 3