Python Loops
Repeat tasks with for loops and while loops.
Imagine you need to display the message Welcome to DevBrainBox ten times. Writing the same print() statement ten times would make the code long and repetitive.
A loop provides a better solution by repeating the same block of code without writing it again and again. Loops save time, reduce errors, and make programs easier to maintain.
In this lesson, you will learn what loops are, why they are useful, and how to use Python's two main loop types: for loops and while loops.
What is a Loop?
A loop is a programming structure that repeatedly executes a block of code until a condition is met or all items in a sequence have been processed.
- Displaying a message multiple times
- Processing items in a list
- Reading data from a file
- Performing repeated calculations
- Creating patterns or tables
Without loops, these tasks would require writing the same code many times.
The for Loop
Use a for loop when you know how many times a task should repeat or when you want to process every item in a collection.
Syntax
for variable in sequence:
# Code to execute
passExample
for i in range(5):
print("Welcome to DevBrainBox")Output
Welcome to DevBrainBox
Welcome to DevBrainBox
Welcome to DevBrainBox
Welcome to DevBrainBox
Welcome to DevBrainBoxrange(5) generates numbers from 0 through 4, causing the loop to run five times.
Using range()
The range() function generates a sequence of integers and is commonly used with for loops. Its stopping value is excluded.
range(stop)
for i in range(5):
print(i)Output
0
1
2
3
4range(start, stop)
for i in range(1, 6):
print(i)Output
1
2
3
4
5range(start, stop, step)
for i in range(2, 11, 2):
print(i)Output
2
4
6
8
10The third argument specifies the step between generated numbers.
Looping Through a String
A for loop can process a string one character at a time.
word = "Python"
for letter in word:
print(letter)Output
P
y
t
h
o
nLooping Through a List
Loops are often used to process collections such as lists. This is easier and more flexible than accessing each item manually.
fruits = ["Apple", "Banana", "Orange"]
for fruit in fruits:
print(fruit)Output
Apple
Banana
OrangeThe while Loop
A while loop repeats as long as its condition remains true.
Syntax
while condition:
# Code to execute
passExample
count = 1
while count <= 5:
print(count)
count += 1Output
1
2
3
4
5count increases after each iteration. Once it becomes greater than 5, the condition is false and the loop stops.
Infinite Loops
If a while condition never becomes false and no other statement exits the loop, it runs indefinitely.
count = 1
while count > 0:
print(count)This loop never ends because count is never changed. Always ensure a while loop has a condition that can eventually become false or a deliberate exit path.
Loop Control Statements
break
break immediately exits the nearest active loop.
for number in range(1, 10):
if number == 5:
break
print(number)Output
1
2
3
4continue
continue skips the rest of the current iteration and moves to the next one.
for number in range(1, 6):
if number == 3:
continue
print(number)Output
1
2
4
5pass
pass is a placeholder that performs no action. It is useful when a syntactically valid loop body is needed temporarily.
for number in range(3):
pass
print("Loop completed.")Nested Loops
A loop inside another loop is a nested loop. For every outer-loop iteration, the inner loop runs through its sequence. Nested loops are useful for tables, grids, combinations, and patterns.
for i in range(1, 4):
for j in range(1, 3):
print(i, j)Output
1 1
1 2
2 1
2 2
3 1
3 2Choosing Between for and while
| Loop | Use It When |
|---|---|
| for | Processing a sequence or repeating a known range of times |
| while | Repetition depends on a condition that changes during execution |
Choosing the appropriate loop makes code easier to understand and maintain.
Key Takeaways
- Loops repeat code without duplication.
- Python provides for and while loops.
- for loops commonly work with range(), lists, strings, and other iterables.
- while loops continue until their condition becomes false.
- break exits a loop immediately.
- continue skips the current iteration and moves to the next one.
- pass acts as a placeholder when no action is needed.
- Nested loops allow one loop to run inside another.
- Ensure while-loop conditions can eventually become false to avoid unintended infinite loops.
- Loops are essential for writing efficient, clean, and reusable Python programs.