loops in python

Save (0)
Close

Recommended

Description

Loops in Python are used to execute a block of code multiple times until a certain condition is met. There are two types of loops in Python:

1. While loop
2. For loop

### While loop:
The while loop in Python is used to loop over a code block as long as the given condition is true. The syntax of while loop is as follows:

while (condition):
#code block

Here, the code block will execute repeatedly as long as the condition is true. The code inside the loop keeps on executing until the condition becomes false. If the condition is initially false, then the code block will never execute.

Example: Printing numbers from 1 to 5 using while loop

i = 1
while i <= 5:
print(i)
i = i + 1

Output:

1
2
3
4
5

### For loop:
The for loop in Python is used to loop over a list or a sequence of elements. The syntax of for loop is as follows:

for element in list:
#code block

Here, the variable ‘element’ will take the value of each element in the list one by one, and the code block will execute for each element.

Example: Printing the items in a list using for loop

fruits = [“apple”, “banana”, “cherry”]
for x in fruits:
print(x)

Output:

apple
banana
cherry

There are a few other concepts related to loops in Python, such as break, continue and pass statements.

The ‘break’ statement is used inside a loop to stop the loop before it has finished its full iteration.

The ‘continue’ statement is used inside a loop to skip the current iteration and move to the next iteration.

The ‘pass’ statement is used as a placeholder inside a loop to avoid syntax errors, and can be used when you don’t need to run any code inside the loop.