Loop in python is a construct that allows you to repeat a block of code for a specific number of times or until a certain condition is met. Loops are essential for iterating over data structures like lists, tuples, and strings.
Looping means repeating something over and over until a particular condition is satisfied. A for loop in Python is a control flow statement that is used to repeatedly execute a group of statements as long as the condition is satisfied. Such a type of statement is also known as an iterative statement.
Python provides two primary types of loops:
- For Loop
- While loop
For Loop in python
Used for sequential traversal, such as going through a list or string. The for loop iterates over an iterable object (like a list or a range) and executes a block of code for each item.
Here’s the basic syntax:
for item in iterable:
# Code to execute
For example, to print numbers from 1 to 10:
for num in range (1, 11):
print(num)
While Loop:
Executes a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the program proceeds to the line immediately after the loop.
The syntax for a while loop is as follows:
while expression:
# Code to execute
For instance, printing “myitschools” five times using a while loop:
count = 0
while count < 3:
count += 1
print("myitschools")
You can also use an else statement with a while loop. The else block is executed when the loop condition becomes false:
count = 0
while count < 3:
count += 1
print ("Hello Geek")
else:
print ("In Else Block")
Notes:
- for loops are ideal for iterating over known sequences (e.g., lists, tuples).
- while loops are useful when the number of iterations is uncertain or depends on dynamic conditions.
- Be cautious with infinite while loops; ensure a proper exit condition.