Python Control Statements
Python Loops
Learn Python Loops with clear explanations, Python examples, and practical programming guidance.
What are Python loops?
Loops repeat a block of code so you can process multiple values or perform a task until a condition changes. They reduce duplicated code and are useful for collections, validation, calculations, and repeated work.
| Loop | Best suited for |
|---|---|
for | Iterating over an iterable such as a list, string, tuple, set, dictionary, or range(). |
while | Repeating while a condition remains true when the number of iterations is not known in advance. |
| Nested loop | Processing one sequence inside another, such as rows and columns in a grid. |
Python for loop
A for loop takes one item at a time from an iterable and assigns it to the loop variable:
for number in range(1, 6):
print(number)2
3
4
5
The loop body is identified by indentation. The value of number changes on each iteration.
Iterating over sequences
A for loop can visit the items in a string, list, tuple, set, or dictionary:
for character in "Python":
print(character)
languages = ["Python", "Java", "SQL"]
for language in languages:
print(language)
student = {"name": "Asha", "experience": 8}
for key, value in student.items():
print(key, value)Iterating directly over items is usually clearer than managing indexes manually. Dictionary iteration uses keys by default; use .items() when both keys and values are needed.
Using range()
range() creates a sequence of numbers without storing every number as a list. Its stop value is exclusive:
| Form | Values produced |
|---|---|
range(stop) | Starts at 0 and stops before stop. |
range(start, stop) | Starts at start and stops before stop. |
range(start, stop, step) | Moves by step, which can be negative. |
print(list(range(5)))
print(list(range(2, 6)))
print(list(range(10, 4, -2)))[2, 3, 4, 5]
[10, 8, 6]
Getting an index with enumerate()
Use enumerate() when you need both the position and the item. It is more readable than looping over range(len(items)):
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)2 banana
3 orange
Python while loop
A while loop repeats as long as its condition is true. Update the state used by the condition so the loop can eventually finish:
counter = 1
while counter <= 5:
print(counter)
counter += 12
3
4
5
Use a while loop for tasks such as retrying input, processing items until a queue is empty, or reading data until an end condition is reached.
else with loops
Python allows an else block after both for and while loops. The else block runs when the loop finishes normally. It does not run when the loop exits through break:
numbers = [2, 4, 6]
for number in numbers:
if number % 2 != 0:
print("Odd number found")
break
else:
print("All numbers are even")This pattern is useful when searching for an item and needing a clear action when no item matches.
Nested loops
A nested loop is a loop inside another loop. The inner loop completes its iterations for every iteration of the outer loop:
for row in range(1, 4):
for column in range(1, 4):
print(row, column)
print("row complete")Nested loops are useful for grids and tables, but their work grows quickly. For large data sets, look for a more efficient algorithm or a library operation.
Loop control statements
| Statement | Effect |
|---|---|
break | Stops the nearest enclosing loop immediately. |
continue | Skips the rest of the current iteration and starts the next one. |
pass | Does nothing; it acts as a placeholder where a statement is required. |
for number in range(1, 6):
if number == 2:
continue
if number == 5:
break
print(number)
for number in range(3):
if number == 1:
pass
print("iteration", number)3
iteration 0
iteration 1
iteration 2
Infinite loops
An infinite loop never reaches a false condition. It is usually caused by forgetting to update the loop state:
counter = 0
while counter < 3:
print(counter)
counter += 1The example is safe because counter changes on every iteration. Avoid an accidental while True loop unless it has a deliberate exit condition, such as break.
Searching with a loop
users = ["Asha", "Ravi", "Mina"]
target = "Ravi"
for user in users:
if user == target:
print("User found")
break
else:
print("User not found")Choosing the right loop
- Use
forwhen iterating over items or a known numeric range. - Use
whilewhen a condition controls how long the work continues. - Use
enumerate()instead of manual index counters when you need positions. - Use
breakto stop a search once the result is known. - Use
continueto skip invalid or unwanted items. - Keep loop bodies small and extract repeated logic into functions.
- Check the condition and update step carefully to avoid infinite loops.
Further Reading
Continue learning with these related Python tutorials:
Continue learning
