Lesson 3 - Understanding Loops in Python: For and While with Examples
Learn how to use for and while loops in Python with practical examples. Understand indentation, avoid infinite loops, and write cleaner, efficient code.
PYTHON
Leonardo Gomes Guidolin
4/6/20251 min read
What Are Loops in Python?
Loops are fundamental for automating tasks in programming. They allow a block of code to run multiple times, whether to iterate over lists, process data, or repeat commands until a condition is met.
In Python, there are two main types of loops:
for loop: Used when you know how many times you want to repeat an action.
while loop: Used when you want to repeat until a condition becomes false.
How to Use for in Python
The for loop is widely used to iterate over sequences like lists, tuples, and strings. It’s essential for working with collections of data.
Example of a basic for loop:
for i in range(5):
print(f"Repetition {i+1}")
Output:
Repetition 1
Repetition 2
Repetition 3
Repetition 4
Repetition 5
The Importance of Indentation in Python
Unlike other languages that use {} or keywords like begin and end, Python uses indentation (spaces at the beginning of a line) to define code blocks.
Correct indentation example:
for i in range(3):
print("This is inside the for loop")
print("This is outside the for loop")
Incorrect indentation example:
for i in range(3):
print("Indentation Error") # Will raise an error
Error:
IndentationError: expected an indented block
How to Use while in Python
The while loop runs a block of code as long as a condition is true. It’s great for dynamic user interaction.
Basic while loop example:
counter = 1
while counter <= 5:
print(f"Attempt {counter}")
counter += 1
Example: Validating user input with while
password = "1234"
entry = ""
while entry != password:
entry = input("Enter the password: ")
print("Access granted!")
How to Avoid Infinite Loops in Python
With while loops, always make sure the condition eventually becomes false—otherwise, your loop will never stop!
Example of an infinite loop (Don’t do this!):
x = 0
while x < 10:
print(x) # x is never updated!
Correct version:
x = 0
while x < 10:
print(x)
x += 1 # Now the loop ends properly
Conclusion
Loops like for and while are essential tools for writing efficient and reusable code in Python. Understanding indentation and loop logic is key for beginners and experienced developers alike.
Experiment with the examples above and try modifying the conditions to see how they work. The more you practice, the better you’ll become at solving problems through code!