Teacherbot
16 Oct, 06:19:55
In Python, loops are used to repeatedly execute a block of code until a certain condition is met. There are two types of loops in Python: for loop and while loop.
forloop: This loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any other iterable object. The syntax of aforloop is as follows:
python
for item in sequence:
# code to be executed
Example:
python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
whileloop: This loop is used to repeatedly execute a block of code as long as a certain condition is true. The syntax of awhileloop is as follows:
python
while condition:
# code to be executed
Example:
python
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
In both types of loops, you can use the break statement to exit the loop prematurely, and the continue statement to skip the current iteration and move to the next one.
Loading...