Python For Loop Tutorial
Introduction
In Python, loops are used to execute a block of code repeatedly. The for loop is one of the most commonly used loops.
This tutorial will guide you through the basics of the Python for loop, how it works, and practical examples to help you master it.
Code is read much more often than it is written.
What is a For Loop?
A for loop in Python is used to iterate over a sequence such as a list, tuple, string, or range.
It executes the block of code inside it once for each item in the sequence.
- Iterates over elements of a sequence.
- Executes code block for each element.
- Simplifies repetitive tasks.
Basic Syntax of For Loop
The basic syntax of a for loop in Python is straightforward and easy to understand.
It uses the 'for' keyword followed by a variable name, the 'in' keyword, and the sequence to iterate over.
- for variable in sequence:
- # code block to execute
Examples of For Loop
Let's look at some practical examples to understand how for loops work in Python.
Iterating Over a List
You can use a for loop to iterate over each item in a list.
Using range() Function
The range() function generates a sequence of numbers, which is commonly used with for loops.
Nested For Loops
For loops can be nested inside another for loop to iterate over multi-dimensional data structures.
This is useful when working with matrices or grids.
- Outer loop runs once per iteration of inner loop.
- Inner loop completes all iterations for each outer loop iteration.
Using else with For Loop
Python allows an optional else block with for loops.
The else block executes after the for loop completes normally, but not if the loop is terminated by a break statement.
- Useful for search operations.
- Indicates loop completed without break.
Examples
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)This example prints each fruit in the list one by one.
for i in range(5):
print(i)This example prints numbers from 0 to 4 using the range function.
for i in range(1, 4):
for j in range(1, 3):
print(f'i={i}, j={j}')This example demonstrates a nested loop printing pairs of i and j values.
for num in range(5):
if num == 3:
break
else:
print('Loop completed without break')The else block does not execute because the loop is broken when num equals 3.
Best Practices
- Use descriptive variable names in for loops for readability.
- Avoid modifying the sequence you are iterating over inside the loop.
- Use range() for numeric iterations instead of manually creating lists.
- Keep the loop body concise and focused on a single task.
- Use else with for loops only when necessary to improve clarity.
Common Mistakes
- Forgetting the colon (:) at the end of the for statement.
- Indentation errors inside the loop body.
- Modifying the list being iterated over, which can cause unexpected behavior.
- Using range() incorrectly, such as off-by-one errors.
- Confusing the use of break and continue statements.
Hands-on Exercise
Print Even Numbers
Write a for loop that prints all even numbers from 0 to 20.
Expected output: 0 2 4 6 8 10 12 14 16 18 20
Hint: Use range() with a step of 2 or check if a number is divisible by 2.
Iterate Over a String
Use a for loop to print each character of the string 'Python'.
Expected output: P y t h o n
Hint: Strings are iterable sequences in Python.
Nested Loop Multiplication Table
Create a nested for loop to print a 3x3 multiplication table.
Expected output: 1 2 3 2 4 6 3 6 9
Hint: Use two loops from 1 to 3 and print the product.
Interview Questions
What is the purpose of a for loop in Python?
InterviewA for loop is used to iterate over a sequence (like a list, tuple, or string) and execute a block of code for each item.
How does the range() function work with for loops?
InterviewThe range() function generates a sequence of numbers which the for loop can iterate over, commonly used for numeric loops.
Can you explain the use of else with a for loop?
InterviewThe else block after a for loop executes only if the loop completes without encountering a break statement.
Summary
The Python for loop is a powerful tool for iterating over sequences and performing repetitive tasks efficiently.
Understanding its syntax, usage with range(), and features like nested loops and else blocks will help you write clean and effective code.
FAQ
Can a for loop iterate over a string in Python?
Yes, strings are iterable sequences, so a for loop can iterate over each character in a string.
What happens if you modify a list while iterating over it with a for loop?
Modifying a list during iteration can lead to unexpected behavior or skipped elements and should generally be avoided.
Is the else block mandatory in a for loop?
No, the else block is optional and only executes if the loop completes without a break.
