Skip to content

Conditions and Loops

Making decisions with if/elif/else and repeating with for and while loops.

What you'll learn

  • if, elif, and else statements for branching
  • The for loop and the range() function
  • The while loop for conditional repetition
  • break and continue to control loop flow
  • Iterating over lists, dicts, and strings

Concept

if / elif / else

Python's conditional syntax is clean and readable. Note the colon after each condition and the indented block:

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"Grade: {grade}")

Python uses indentation (4 spaces by convention) to define the block — there are no curly braces.

for Loops

Python's for loop iterates over any iterable — lists, strings, dicts, ranges:

# Iterate over a list
for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

# Iterate over a string
for char in "Hello":
    print(char)

# Use range() for a count-controlled loop
for i in range(5):       # 0, 1, 2, 3, 4
    print(i)

for i in range(2, 10, 2):  # 2, 4, 6, 8 (start, stop, step)
    print(i)

while Loops

A while loop runs as long as the condition is true:

count = 5
while count > 0:
    print(count)
    count -= 1
print("Liftoff!")

Be careful: if the condition never becomes false, you get an infinite loop. Always make sure the loop variable changes.

break and continue

  • break — exit the loop immediately
  • continue — skip the rest of this iteration and go to the next
for n in range(10):
    if n == 3:
        continue  # skip 3
    if n == 7:
        break     # stop at 7
    print(n)      # 0, 1, 2, 4, 5, 6

Iterating Dicts and Using enumerate()

user = {"name": "Ada", "age": 25, "role": "admin"}

# Iterate keys and values together
for key, value in user.items():
    print(f"{key} = {value}")

# Get both index and value while iterating a list
for index, fruit in enumerate(["apple", "banana", "cherry"]):
    print(f"{index}: {fruit}")

enumerate() is the Pythonic way to get both the index and the value — much cleaner than tracking an index manually.

The else Clause on Loops

Python loops can have an else clause that runs only if the loop completed without hitting break:

for n in range(2, 10):
    if n == 5:
        break
else:
    print("Loop completed without break")

This is useful for search loops where you want to do something if the item was not found.

Example

              # if / elif / else
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(f"Score {score} earns grade {grade}")

# for loop with range
print("Countdown:")
for i in range(3, 0, -1):
    print(f"  {i}...")

# while loop with a safety counter
attempts = 0
max_attempts = 3
while attempts < max_attempts:
    print(f"Attempt {attempts + 1}")
    attempts += 1

# break and continue
print("Even numbers up to 10 (skipping 6):")
for n in range(1, 11):
    if n % 2 != 0:
        continue  # skip odd numbers
    if n == 6:
        break     # stop at 6
    print(f"  {n}")

# enumerate for index + value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"  {index}: {fruit}")

# Iterate a dictionary
user = {"name": "Ada", "age": 25}
for key, value in user.items():
    print(f"  {key} = {value}")
            

Shows if/elif/else grading, a for countdown, a while retry loop, break/continue filtering, enumerate for index+value, and dict iteration. These patterns cover most daily loop usage.

Try it

  • Text Counter

    Counting characters and words is a classic loop task in Python.

  • Math Evaluator

    Evaluate expressions that often appear in loop conditions.

Common mistakes

The mistake

Forgetting the colon after if/for/while statements

The fix

Python requires a colon at the end of if, elif, else, for, and while lines. The error 'SyntaxError: expected :' is the most common beginner mistake — always add the colon.

The mistake

Creating an infinite while loop by not updating the condition variable

The fix

Inside a while loop, always update the variable that the condition checks. Add a safety counter as a backup: if safety > 1000: break to prevent runaway loops during development.

Related Cheatsheets

Practice Conditions and Loops

2 exercises

Practice Conditions and Loops

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors