What are Loops?
A loop in Python is used to run a block of code repeatedly while a specific condition remains true.
Loops help reduce repetitive code and make programs more efficient, such as when printing numbers or processing items in a list.
Types of Loops in Python
- for loop – Used to iterate over a sequence (like list, tuple, string, etc.)
- while loop – Used to repeat a block of code as long as the given condition is true
Where are Loops Used?
- Repeating a task multiple times (e.g., printing a message 10 times)
- Iterating over elements of a collection (list, dictionary, etc.)
- Automating repetitive logic like calculations, searching, etc.
Note: Loops can be controlled using statements like break
,
continue
, and pass
to manage how and when they stop or skip iterations.
Summary
- Loops are used to repeat a block of code multiple times.
- Python provides
for
andwhile
loops. - Control statements like
break
,continue
, andpass
help manage loop behavior.