Skip to main content

Loops in Python

Loops allow executing a block of code repeatedly as long as a condition is met. They are fundamental for automating repetitive tasks and traversing data structures like lists, dictionaries, or text strings.

Python has two main types of loops:


for Loop​

It is used to iterate over elements of a sequence (like a list, a string, or a range of numbers).

Syntax:​

for variable in iterable:
# Code block

Example:​

fruits = ["apple", "pear", "grape"]

for fruit in fruits:
print(fruit)

> Result:

apple
pear
grape

You can also use for with the range() function to repeat a block a certain number of times:

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

> Result:

0
1
2
3
4

while Loop​

Repeats the code block while a condition is true.

Syntax:​

while condition:
# Code block

Example:​

counter = 1

while counter <= 3:
print(counter)
counter += 1

> Result:

1
2
3

Useful keywords​

KeywordDescription
breakExits the loop immediately.
continueSkips the current iteration and moves to the next one.
elseExecutes if the loop finishes without having used break.

Example with break:​

for number in range(10):
if number == 5:
break
print(number)

> Result:

0
1
2
3
4

Example with continue:​

for number in range(5):
if number == 2:
continue
print(number)

> Result:

0
1
3
4

Example with else in loops:​

for i in range(3):
print(i)
else:
print("The loop finished correctly")

> Result:

0
1
2
The loop finished correctly

Differences between for and while​

Featureforwhile
Ideal for...Iterating over sequencesExecuting while a condition is met
Iteration controlBased on the iterableBased on logical condition
Infinite loop riskLowHigh if the condition is not changed

Best practices​

  • Use for when you know how many times you need to iterate or have an iterable structure.
  • Use while when you do not know for sure how many iterations will be made.
  • Always make sure loops have a clear exit condition.
  • Avoid nesting multiple loops if you can simplify the logic.
  • Use meaningful variable names inside loops.

Loops are fundamental tools for automating tasks, traversing data structures, and controlling the flow of execution in your Python programs. Mastering their use will help you write more efficient, clean, and powerful code.