beginner22 min

Conditionals and Loops

Make decisions with if/elif/else and repeat work with for and while loops.

What you'll learn

  • Branch program logic using if, elif, and else
  • Iterate over sequences and ranges with a for loop
  • Repeat work conditionally with a while loop, avoiding infinite loops

Prerequisites

Explanation

Programs become useful the moment they can make decisions and repeat work. Python gives you two tools for that: conditionals and loops — both built on the indentation rules from the previous lesson.

if / elif / else. An if statement runs its indented block only when a condition is True. You can chain additional checks with elif ("else if"), and catch everything else with a final else. Python checks each condition in order and runs the block for the first one that's true, then skips the rest — so order matters when conditions overlap.

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

for loops. A for loop repeats its block once for each item in something iterable — a string, a list, or a range of numbers. range(5) produces the numbers 0, 1, 2, 3, 4 — five values starting at zero, not including 5. range(2, 6) gives 2, 3, 4, 5, and range(0, 10, 2) steps by 2. This "stop value excluded" rule trips up almost everyone at first, so it's worth committing to memory early: range(n) always produces exactly n numbers.

while loops. A while loop keeps running its block as long as a condition stays True, checked fresh before every repetition. Unlike a for loop, nothing automatically moves you toward the end — you are responsible for changing something inside the loop body so the condition eventually becomes false. Forget that step, and you've written an infinite loop that never returns control to the rest of your program.

Choosing between them. Reach for for when you know in advance what you're iterating over (a list of items, a fixed count). Reach for while when you're repeating "until some condition changes," and you don't know ahead of time how many repetitions that will take — for example, reading input until a sentinel value appears, or accumulating a total until it crosses a threshold.

Boolean operators. Conditions can be combined with and, or, and not to express more nuanced logic, such as age >= 13 and age < 20 for "is a teenager."

Together, conditionals and loops are the two ingredients behind almost every algorithm you'll ever write: branch on data, repeat over data. Everything from validating a form to processing a spreadsheet builds on exactly these two patterns.

Example

A for loop assigns a letter grade to each score, then a while loop computes the average.

scores = [55, 82, 91, 40, 76]

for score in scores:
    if score >= 90:
        grade = "A"
    elif score >= 80:
        grade = "B"
    elif score >= 70:
        grade = "C"
    elif score >= 60:
        grade = "D"
    else:
        grade = "F"
    print(f"Score {score} -> Grade {grade}")

total = 0
count = 0
while count < len(scores):
    total += scores[count]
    count += 1

print("Average:", total / len(scores))

Try it yourself

Change the range to go from 1 to 30 (inclusive) and press Run.

Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.

Loading editor…

Guided exercise

Guided exercise

Complete the for loop so that even_count ends up holding the number of even values in numbers.

Checks: even_count is an int · even_count equals 4 · plus 1 hidden check

Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.

Loading editor…

Stuck? Get a hint.

Independent exercise

Independent exercise

Using a while loop, find how many counting numbers (1, 2, 3, ...) must be added together before the running total reaches at least target = 500. Store the count in terms_needed and the final total in total.

Checks: total reaches at least the target · terms_needed equals 32 · plus 2 hidden checks

Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.

Loading editor…

Stuck? Get a hint.

Common mistakes

  • Forgetting the colon (:) at the end of an if, elif, else, for, or while line.
  • Assuming range(1, 5) includes 5 — the stop value is always excluded, so it produces 1, 2, 3, 4.
  • Writing a while loop whose condition variable never changes inside the loop body, causing an infinite loop.
  • Using = (assignment) where == (comparison) was intended inside a condition.

Knowledge check

Knowledge check

1. What does range(5) produce when looped over?
2. Which keyword lets you check an additional condition only if a previous if failed?
3. What is most likely to happen if a while loop's condition variable is never updated inside the loop?
4. What determines which lines belong to the body of a for loop?

Takeaway

if/elif/else branches your logic, for loops repeat over known sequences, and while loops repeat until a condition you control becomes false.

Summary

Conditionals (if/elif/else) let a program branch based on data, while for and while loops let it repeat work — for when you know what you're iterating over, while when you're repeating until a condition changes. range() is the most common way to loop a fixed number of times, always excluding its stop value.

References

Your notes

Notes save automatically.

Finished this lesson?

Mark it complete to track your progress and schedule a future review.