Python Docs

Loops

What Are Loops ?

Loops let you run a block of code multiple times without repeating it manually.

Python has two main types of loops:

  • for loop — repeats a fixed number of times or iterates over items.
  • while loop — repeats while a condition is true.

1. The for Loop

A for loop is commonly used to iterate over items like lists, strings, or ranges of numbers.

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-oriented programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set, etc.

Example

Print each fruit in a fruit list:

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

Output:

apple
banana
cherry

2. The while Loop

A while loop runs as long as a condition remains true.


syntax :

while condition:

#block of code

The condition should be something that can be evaluated as True or False (a Boolean expression).

The code inside the loop (indented block) keeps running repeatedly until the condition becomes False.

Example

Print i as long as i is less than 6:

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

Output:

1
2
3
4
5