Loops in Python
In the previous lesson, we learned about Conditional Statements and how programs make decisions using "if", "else", and "elif". Today, we will learn about Loops, which are used to repeat a block of code multiple times.
Loops are important because they help programmers avoid writing repetitive code and make programs more efficient.
What are Loops?
Loops are used to execute a block of code repeatedly until a condition is met.
Python mainly provides:
- "for" loop
- "while" loop
The for Loop
A "for" loop is used to iterate over a sequence such as:
- Lists
- Strings
- Tuples
- Ranges
Syntax
for variable in sequence:
# code to execute
Example
for i in range(5):
print(i)
Output
0
1
2
3
4
Understanding range()
The "range()" function generates a sequence of numbers.
Example
for number in range(1, 6):
print(number)
Output
1
2
3
4
5
Looping Through a String
Example
word = "Python"
for letter in word:
print(letter)
Output
P
y
t
h
o
n
Looping Through a List
Example
languages = ["Python", "Java", "C++"]
for language in languages:
print(language)
Output
Python
Java
C++
The while Loop
A "while" loop executes as long as the condition remains "True".
Syntax
while condition:
# code to execute
Example
count = 1
while count <= 5:
print(count)
count += 1
Output
1
2
3
4
5
Infinite Loops
An Infinite Loop happens when the condition never becomes "False".
Example
while True:
print("Python")
This loop will continue forever unless stopped manually.
break Statement
The "break" statement is used to stop a loop immediately.
Example
for i in range(1, 10):
if i == 5:
break
print(i)
Output
1
2
3
4
The continue Statement
The continue statement is used to skip the current iteration and move to the next. It does not stop the entire loop, only the code following it inside the loop for that specific cycle.
Example:
for item in ["Apple", "Banana", "STOP", "Cherry"]:
if item == "STOP":
continue # Skip this item
print(item)
output
Apple
Banana
Cherry
Nested Loops
A loop inside another loop is called a nested loop. The inner loop executes completely for each iteration of the outer loop. This is useful for working with multi-dimensional data like matrices.
Example:
adj = ["red", "big"]
fruits = ["apple", "banana"]
for x in adj:
for y in fruits:
print(x, y)
output
red apple
red banana
big banana
Conclusion
Congratulations on finishing Day 6! Today, we learned:
Loops are essential for automation, repetition, and efficiency.
The for loop is best for iterating over sequences (lists, ranges, strings).
The while loop runs as long as a specified condition is true.
break terminates the entire loop immediately.
continue skips only the current iteration.
Mastering loops will significantly improve your ability to handle repetitive tasks and complex data. Great work so far!
Top comments (0)