Introduction
Loops are a programming technique used in most programming languages. The primary purpose of loops is to repeat tasks until some condition is met. In this article, we will discuss the different types of loops and their use cases.
Types of loops in Python
There are two types of loops in Python:
- The for loop
- The while loop
The 'for' loop
The for loop is the most common type of loop in Python. It is used to iterate over a sequence and execute the body of the loop for each element.
The syntax for a simple Python for loop is as follows:
for <variable> in <sequence>:
Statements-to-be-executed
Example of a for loop in Python:
for i in [1, 2, 3, 4, 5]:
print(i)
Output:
2
3
4
5
The 'while' loop
A while loop is a control structure that allows us to execute a block of code multiple times while a condition is true. If the condition becomes false, the loop breaks and execution continues.
Syntax:
while (condition):
Execute this block
Example of a while loop in Python:
i = 0
while i < 5:
print(i)
i = i + 1
Output:
1
2
3
4
