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:

  1. for loop
  2. 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

PYTHON
1fruits = ["apple", "banana", "cherry"]
2for fruit in fruits:
3 print(fruit)
▶ Output will appear here.

Example 2: Using range()

A function that generates a sequence of numbers for controlled iterations.

PYTHON
1for i in range(1, 6):
2 print(i)
▶ Output will appear here.

Example 3: Using for with String

A for loop that iterates through each character in a string.

PYTHON
1for letter in "Python":
2 print(letter)
▶ Output will appear here.

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

PYTHON
1count = 1
2while count <= 5:
3 print(count)
4 count += 1
▶ Output will appear here.

Example 2: Infinite Loop (Use with Care!)

PLAINTEXT
1while True:
2 print("This will run forever!")
3 break # stop the loop using break
▶ Output will appear here.

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:

PYTHON
1for i in range(1, 4):
2 for j in range(1, 4):
3 print(f"i={i}, j={j}")
▶ Output will appear here.

Loop Control Statements

Python provides special statements to control how loops behave.

StatementDescriptionExample Meaning
breakTerminates the loop immediatelyStop the loop when i==3
continueSkips the current iteration and moves to the nextSkip printing when i==3
passDoes nothing; used as a placeholderUsed for creating empty loops or blocks

Example:

PYTHON
1for i in range(1, 6):
2 if i == 3:
3 continue
4 print(i)
▶ Output will appear here.

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:

PYTHON
1for i in range(1, 4):
2 print(i)
3else:
4 print("Loop completed successfully!")
▶ Output will appear here.

Note: Don’t get confuse

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges