How to loop in Python

Loops in Python allow you to repeat a block of code until a certain condition is met. There are two types of loops in Python: for loops and while loops. Here are examples of each type of loop: 

For Loop in Python

A for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable object. Here’s an example:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
Python

This will output:

apple
banana
cherry
XML

While Loop in Python

A while loop repeats a block of code as long as a certain condition is true. Here’s an example:

counter = 1
while counter <= 5:
    print(counter)
    counter += 1
Python

This will output:

1
2
3
4
5
XML

In both for and while loops, you can use the break statement to exit the loop early, and the continue statement to skip to the next iteration of the loop.

Bonus: Looping Through a Dictionary 

When looping through a dictionary, you can use the items() method to get both the key and value of each item in the dictionary. Here’s an example:

person = {"name": "John Doe", "age": 30, "city": "New York"}

for key, value in person.items():
    print(f"{key}: {value}")
Python


This will output:

name: John Doe
age: 30
city: New York
XML

This way, you don’t have to use the keys to access the values, which can make your code more readable and easier to write.

Leave a Reply