What is a loop in Python?
A loop runs a block of code more than once. Instead of writing print() five times, you can tell Python what to repeat and when to stop. This is useful for adding scores, reading lists, processing records, and—eventually—checking data for AI projects. All examples below work with standard Python 3; you do not need packages or an API key.
Use a for loop when you have a sequence
Copy this into a file named loop_practice.py, predict its output, and run it. The indented line belongs to the loop:
languages = ["Python", "SQL", "JavaScript"]
for language in languages:
print("I'm learning", language)
Expected output:
I'm learning Python
I'm learning SQL
I'm learning JavaScript
The variable language takes one value from the list at a time. You do not need to change the list while iterating through it. If you want numbers, range(3) produces 0, 1, and 2, whereas range(1, 4) produces 1, 2, and 3.
for number in range(1, 4):
print("Mission", number)
Expected lines are Mission 1, Mission 2, and Mission 3. The second argument to range() is excluded; that difference causes many first-week bugs.
Use a while loop when you have a condition
A while loop repeats as long as its condition is true. You must make progress toward stopping, or you can create an infinite loop:
remaining = 3
while remaining > 0:
print("Tasks left:", remaining)
remaining -= 1
print("All done!")
Expected output:
Tasks left: 3
Tasks left: 2
Tasks left: 1
All done!
The statement remaining -= 1 reduces the counter. Remove it as a thought experiment: the condition would remain true and the loop would not end. If you accidentally run an infinite loop, use your editor's Stop control or Ctrl+C in a terminal.
Mini-project: add up your study minutes
Suppose you studied for 10, 15, and 20 minutes. Instead of adding those numbers manually, use a running total. This is a useful pattern whenever you process many observations:
sessions = [10, 15, 20]
total = 0
for minutes in sessions:
total += minutes
print("Total minutes:", total)
print("Sessions completed:", len(sessions))
Expected output:
Total minutes: 45
Sessions completed: 3
The variable total starts at zero, then grows by each value in the list. Once the pattern makes sense, try changing sessions to [5, 5, 25, 15]. Predict the result before pressing Run.
Three common loop mistakes
- Forgetting the colon: write
for item in items:andwhile count > 0:. - Incorrect indentation: Python uses indentation to decide which statements repeat. Put the repeated statements at the same indent level (commonly four spaces).
- Off-by-one errors:
range(5)generates five numbers beginning at zero, not the numbers 1 through 5.
Four exercises with answers
Try each one without looking at the answer first. You can copy the code into any Python 3 interpreter.
- Write a loop that prints the numbers 1, 2, 3, and 4.
- Sum
[4, 6, 10]using aforloop. - Change the earlier
whileloop so it starts at 2. What is printed? - Count how many names appear in
["Asha", "Bilal", "Chen"], without callinglen().
Reveal the worked solutions
# Exercise 1
for number in range(1, 5):
print(number)
# Exercise 2
total = 0
for item in [4, 6, 10]:
total += item
print(total) # 20
# Exercise 3
remaining = 2
while remaining > 0:
print(remaining)
remaining -= 1
# prints 2, then 1
# Exercise 4
count = 0
for name in ["Asha", "Bilal", "Chen"]:
count += 1
print(count) # 3
The goal is to understand the counter and stopping condition, not memorize syntax without testing it.
What should you learn after loops?
Once you can predict each iteration, practice combining loops with conditions, lists, and functions. Start with Python if, elif and else, including a worked decision-making mini-project. A function gives a name to code you want to reuse. Continue with our beginner Python functions tutorial or try the rule-based Python chatbot, which uses a loop to keep reading questions.
If you're new to Python, return to the first 20-minute Python program. For more practice, try 10 beginner Python exercises with solutions before moving to the AI engineering roadmap. Continue learning with free seven-day Python-for-AI practice plan.