Python Loops Basics: A Beginner's Guide
Welcome! Loops are one of the most important concepts in programming. They allow you to repeat a block of code multiple times without writing it over and over. In this tutorial, you'll learn:
- What is a loop and why we use it
- The
forloop – iterating over sequences - The
whileloop – repeating until a condition changes - Loop control:
breakandcontinue - Nested loops (loops inside loops)
- A simple challenge to test your skills
No prior experience needed. Let's start!
1. What is a Loop?
A loop is a way to repeat a block of code multiple times. Instead of writing the same code 10 times, you write it once inside a loop and tell Python how many times to repeat it.
Why use loops?
- Save time and reduce code duplication
- Process lists, strings, and other collections easily
- Automate repetitive tasks
Python has two main types of loops:
forloop – used when you know how many times to repeat (or when looping over items)whileloop – used when you want to repeat until a condition becomes false
2. The for Loop
The for loop is used to iterate over a sequence (like a list, tuple, string, or range). Each time the loop runs, it takes the next item from the sequence and executes the code block.
Example 1: Loop over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
Example 2: Loop over a string (character by character)
name = "Python"
for letter in name:
print(letter)
# Output:
# P
# y
# t
# h
# o
# n
Example 3: Using range() to repeat a number of times
range(n) generates numbers from 0 to n-1.
for i in range(5):
print("Iteration:", i)
# Output:
# Iteration: 0
# Iteration: 1
# Iteration: 2
# Iteration: 3
# Iteration: 4
Example 4: range(start, end, step)
# Count from 1 to 10, stepping by 2
for i in range(1, 11, 2):
print(i)
# Output: 1, 3, 5, 7, 9
Example 5: Sum of first 10 numbers
total = 0
for i in range(1, 11):
total = total + i
print("Sum of 1 to 10 is:", total)
# Output: Sum of 1 to 10 is: 55
When to use for loop:
- When you have a list, string, or range to go through
- When you know exactly how many times to repeat
- When you want to do something with each item in a collection
3. The while Loop
The while loop repeats as long as a condition is True. You must update the condition inside the loop, otherwise it will run forever (infinite loop).
Example 1: Basic while loop
count = 1
while count <= 5:
print("Count is:", count)
count = count + 1 # important: update the variable
# Output:
# Count is: 1
# Count is: 2
# Count is: 3
# Count is: 4
# Count is: 5
Example 2: Countdown timer
timer = 5
while timer > 0:
print("T-minus", timer)
timer = timer - 1
print("Blast off!")
# Output:
# T-minus 5
# T-minus 4
# T-minus 3
# T-minus 2
# T-minus 1
# Blast off!
Example 3: Keep asking until user guesses correct (simulated)
secret_number = 7
guess = 0
while guess != secret_number:
guess = int(input("Guess a number between 1 and 10: "))
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
print("You got it!")
⚠️ Important: Avoid infinite loops!
If you forget to update the variable inside the loop, the condition never becomes false:
# INFINITE LOOP - DON'T RUN THIS!
# x = 1
# while x < 10:
# print(x)
# # missing x = x + 1 → will run forever
Always make sure something inside the loop changes the condition.
When to use while loop:
- When you don't know how many times you need to repeat
- When you want to keep doing something until a condition is met
- When waiting for user input or external event
4. Loop Control: break and continue
Sometimes you want to stop a loop early or skip certain iterations. That's where break and continue come in.
break – Exits the loop immediately
# Stop when we find the number 3
for i in range(1, 6):
if i == 3:
break
print(i)
# Output:
# 1
# 2
Another example: Stop at the letter 'e'
word = "Python is great"
for letter in word:
if letter == 'e':
break
print(letter)
# Output: P y t h o n i s (space prints, stops before 'e')
continue – Skips the rest of the current iteration and goes to the next one
# Skip even numbers
for i in range(1, 6):
if i % 2 == 0:
continue
print(i)
# Output:
# 1
# 3
# 5
Skip vowels in a string
text = "hello"
for letter in text:
if letter in "aeiou":
continue
print(letter)
# Output:
# h
# l
# l
5. Nested Loops – Loop Inside a Loop
A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
Example 1: Simple nested loop
for i in range(1, 4): # outer loop
for j in range(1, 4): # inner loop
print(f"i={i}, j={j}")
# Output:
# i=1, j=1
# i=1, j=2
# i=1, j=3
# i=2, j=1
# i=2, j=2
# i=2, j=3
# i=3, j=1
# i=3, j=2
# i=3, j=3
Example 2: Multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i} x {j} = {i*j}")
print("---") # separator between tables
# Creates multiplication tables for 1 through 5
Example 3: Drawing a rectangle with stars
rows = 3
cols = 5
for r in range(rows):
for c in range(cols):
print("*", end="")
print() # new line after each row
# Output:
# *****
# *****
# *****
6. Quick Loop Reference
| Loop Type | Syntax | When to Use |
|---|---|---|
for |
for item in sequence: |
Loop over list, string, range, etc. |
while |
while condition: |
Repeat until condition false |
break |
break |
Exit loop immediately |
continue |
continue |
Skip to next iteration |
7. 🎯 Simple Challenge: Number Guessing Game
Instructions: Write a Python program that does the following:
- Pick a secret number (for example,
secret = 7). - Ask the user to guess a number between 1 and 10.
- Keep asking until the user guesses correctly.
- If the guess is too low, print "Too low!"
- If the guess is too high, print "Too high!"
- When they guess correctly, print "Congratulations! You got it!" and stop.
- Bonus: Count how many guesses they made and print it at the end.
Challenge Solution (try to solve yourself first, then check below):
# Solution to the challenge
secret = 7
guess_count = 0
while True:
guess = int(input("Guess a number between 1 and 10: "))
guess_count = guess_count + 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"Congratulations! You got it in {guess_count} guesses!")
break
Another challenge (for extra practice): Print all even numbers from 2 to 20 using a for loop.
# Solution:
for i in range(2, 21, 2):
print(i)
Practice task: Create a list of your 5 favorite movies. Use a for loop to print them with numbers (1. Movie, 2. Movie...).
# Solution:
movies = ["Inception", "The Matrix", "Interstellar", "Gladiator", "Titanic"]
for index in range(len(movies)):
print(f"{index + 1}. {movies[index]}")
8. Common Beginner Mistakes (And How to Avoid Them)
- Forgetting the colon (
:) – Every loop needs a colon at the end of the line. - Forgetting indentation – The code inside the loop MUST be indented (usually 4 spaces).
- Infinite while loops – Always update the condition variable inside the loop.
- Using
=instead of==in conditions –=is assignment,==is comparison. - Looping over
Noneor empty variable – Make sure your sequence exists before looping.
# Wrong (missing colon):
# for i in range(5)
# print(i)
# Wrong (missing indentation):
# for i in range(5):
# print(i) # This line is not indented!
# Correct:
for i in range(5):
print(i)
9. Summary
forloop – best for going through lists, strings, and ranges.whileloop – best when you need to repeat until a condition changes.break– stops the loop entirely.continue– skips to the next iteration.- Nested loops – loops inside loops (use carefully, they can be slow).
What to learn next? After mastering basic loops, practice with:
- List comprehensions (compact loops)
- The
enumerate()function for index and value - The
zip()function for looping over multiple lists at once
Congratulations! You've completed the Python Loops Basics tutorial. Practice these examples, try the challenge, and you'll be comfortable with loops in no time. Happy coding! 🐍
You need to be logged in to participate in this discussion.