Loop

 

1. for Loop:

The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) or other iterable objects. It has the following syntax:

for variable in iterable: # Code to be executed in each iteration
Here's a simple example:

fruits = ["apple", "banana", "cherry"
for fruit in fruits: 
print(fruit)
This loop iterates over the list fruits, and in each iteration, the variable fruit takes on the value of the current element in the list.

2. while Loop:

The while loop is used to repeatedly execute a block of code as long as a given condition is true. It has the following syntax:

while condition: # Code to be executed as long as the condition is true

Here's an example:


count = 0 while count < 5
print(count) count += 1
This loop prints the values of count from 0 to 4. The loop continues to execute as long as the condition count < 5 is true.

Loop Control Statements:



Python provides two loop control statements that allow you to manipulate the flow of a loop:

break: Terminates the loop prematurely, and the program continues with the next statement after the loop.


continue: Skips the rest of the code inside the loop for the current iteration and proceeds with the next iteration.

Iterating Over Sequences:

In Python, you often use loops to iterate over sequences like lists, strings, or ranges. The range() function is commonly used to generate a sequence of numbers for iteration.

for i in range(5): 
print(i)


This prints the numbers from 0 to 4.

Loops are fundamental for creating efficient and flexible programs, and they play a crucial role in various programming tasks.

Post a Comment

0 Comments