Looping Statements (Iteration)
Python tutorial · PySpark.in
Looping Statements (Iteration)
Loops are used to execute a block of code repeatedly until a certain condition is met.This process is called iteration.Instead of writing the same line of code multiple times, we can use loops to perform repetitive tasks efficiently.
Types of Loops in Python
Python provides two main types of loops:
- for loop
- while loop
Additionally, we use nested loops and loop control statements like break, continue, and pass to control loop behavior.
for Loop
The for loop is used to iterate over a sequence such as a list, tuple, dictionary, string, or range of numbers.
Example1 : Looping through a List
Example 2: Using range()
A function that generates a sequence of numbers for controlled iterations.
Example 3: Using for with String
A for loop that iterates through each character in a string.
while Loop
The while loop runs as long as a condition is True.When the condition becomes False, the loop stops.
Example 1: Basic while Loop
Example 2: Infinite Loop (Use with Care!)
Nested Loops
You can use one loop inside another.These are called nested loops and are often used for working with 2D data (like matrices).
Example:
Loop Control Statements
Python provides special statements to control how loops behave.
| Statement | Description | Example Meaning |
|---|---|---|
| break | Terminates the loop immediately | Stop the loop when i==3 |
| continue | Skips the current iteration and moves to the next | Skip printing when i==3 |
| pass | Does nothing; used as a placeholder | Used for creating empty loops or blocks |
Example:
Using Else with Loops
Python allows an else block with both for and while loops.
The else part is executed only when the loop completes normally (i.e., no break occurs).
Example:
Note: Don’t get confuse
- Use for loops when you know how many times to iterate.
- Use while loops when the number of iterations is unknown.
- Use break, continue, and pass to control loop execution.
- Nested loops are useful for multi-dimensional data.
- else with loops provides clean post-loop handling.
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges