Loops allow a program to repeat a block of code multiple times.
In Python, loops are commonly used to process collections of data,
perform repeated calculations, and automate tasks.
Python provides two primary looping constructs:
for loops and while loops.
for loops
A for loop is used to iterate over a
sequence of values, such as a list, a string, or a range of numbers.
The loop runs once for each item in the sequence.
for i in range(5):
print(i)
In this example, the loop variable i takes on the values
0 through 4.
The loop automatically stops when the sequence is exhausted.
for loops are ideal when:
- you know how many times the loop should run,
- you are iterating over an existing collection of items,
- each iteration is independent of the others.
while loops
A while loop repeats a block of code
as long as a condition remains true.
The condition is checked before each iteration.
count = 0
while count < 5:
print(count)
count += 1
In this example, the loop continues until count reaches 5.
Unlike a for loop, the programmer is responsible for updating the
condition inside the loop.
while loops are useful when:
- you do not know in advance how many iterations are needed,
- the loop depends on a changing condition or user input,
- the loop should stop based on a logical test rather than a count.
Choosing between for and while
In many cases, either type of loop could be used, but choosing the right one improves clarity and reduces errors.
-
Use a
forloop when iterating over a known sequence or range. -
Use a
whileloop when repetition depends on a condition that may change unpredictably.
Big idea: for loops are best for structured, count-controlled
repetition, while while loops are best for condition-controlled
repetition.