AnyLearn
All lessons
Programmingbeginner

Decisions and Loops: Making a Program Choose and Repeat

Teach a program to react and repeat: booleans and comparisons, if/elif/else chains where order is logic, while and for loops, range() and its excluded stop, break and continue, and the skill that matters most, tracing a loop by hand. Ends with a working number-guessing game.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 10

True, False, and comparisons

A program that does the same thing on every run is a calculator. To react to its input it needs decisions, and decisions start with values that are True or False. Comparisons produce them:

ExpressionMeaningExampleResult
==Equal to3 == 3.0True
!=Not equal to5 != 5False
< >Less than, greater than"a" < "b"True
<= >=At most, at least10 >= 10True

Combine them with and, or and not:

age = 20
has_ticket = False
print(age >= 18 and has_ticket)   # False: both must be True
print(age >= 18 or has_ticket)    # True: one is enough
print(not has_ticket)             # True

Strings compare alphabetically by character code, which is why "a" < "b" is True. Note that 3 == 3.0 is also True: an int and a float with the same value compare equal.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. True, False, and comparisons

A program that does the same thing on every run is a calculator. To react to its input it needs decisions, and decisions start with values that are True or False. Comparisons produce them:

ExpressionMeaningExampleResult
==Equal to3 == 3.0True
!=Not equal to5 != 5False
< >Less than, greater than"a" < "b"True
<= >=At most, at least10 >= 10True

Combine them with and, or and not:

age = 20
has_ticket = False
print(age >= 18 and has_ticket)   # False: both must be True
print(age >= 18 or has_ticket)    # True: one is enough
print(not has_ticket)             # True

Strings compare alphabetically by character code, which is why "a" < "b" is True. Note that 3 == 3.0 is also True: an int and a float with the same value compare equal.

2. if, elif, else

An if statement runs a block of code only when its condition is True. Add elif ("else if") for further checks and else for everything left over:

score = 80

if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 50:
    grade = "C"
else:
    grade = "Fail"

print(grade)   # B

Python checks the conditions from the top and runs only the first block whose condition is True, then skips the rest. With score = 80, the first test fails, the second passes, and the elif score >= 50 line is never even looked at.

The colon at the end of each condition and the indentation beneath it are not decoration. Indentation is how Python knows which lines belong to the block. The convention, from Python's style guide PEP 8, is four spaces per level.

Gotcha: if score = 90: is a SyntaxError. A single = assigns; comparison needs ==. Python's error message even suggests the fix.

3. Why the order of elif matters

Because only the first matching branch runs, the order of your conditions is part of the logic. Here is the same grading code with the checks written bottom-up:

score = 95

if score >= 50:
    grade = "C"
elif score >= 75:
    grade = "B"
elif score >= 90:
    grade = "A"
else:
    grade = "Fail"

print(grade)   # C

A score of 95 earns a C. The first condition, score >= 50, is already True, so Python takes that branch and never reaches the others. Run it with 95, 80, 50 and 49 and you get C, C, C, Fail: the A and B branches are unreachable.

Key idea: When conditions overlap, put the most specific one first. For thresholds that means checking from the highest down (or the lowest up with <), so that each branch only catches what the ones above it did not.

This is a logic error: the program runs without complaint and gives a wrong answer. No error message will point you to it, only testing with known inputs will.

4. How Python walks an if / elif / else chain

Each test is only reached when every test above it was False. The first True wins.

flowchart TD
  A["Is score >= 90 ?"] --> G1["True: grade = A"]
  A --> B["False: is score >= 75 ?"]
  B --> G2["True: grade = B"]
  B --> C["False: is score >= 50 ?"]
  C --> G3["True: grade = C"]
  C --> G4["False: else, grade = Fail"]
  G1 --> P["print(grade)"]
  G2 --> P
  G3 --> P
  G4 --> P

5. while: repeat until something changes

A while loop repeats its block as long as its condition stays True:

n = 3
while n > 0:
    print(n)
    n = n - 1
print("Liftoff")

This prints 3, 2, 1, Liftoff. Before each pass Python rechecks n > 0; when n reaches 0 the condition is False and execution continues after the block.

while fits when you do not know in advance how many repetitions you need. How many years does 1,000 take to reach 2,000 at 5% interest a year?

savings = 1000
years = 0
while savings < 2000:
    savings = savings * 1.05
    years = years + 1
print(years)   # 15

After 14 years the balance is about 1,980; after 15 it is about 2,079, so the loop stops at 15.

Gotcha: If nothing inside the loop ever makes the condition False, it runs forever. Forget n = n - 1 above and the program prints 3 until you stop it with Ctrl+C.

6. for: repeat over a sequence

A for loop takes each item of a sequence in turn. Strings and lists are sequences, and so is range(), which generates numbers:

CallProducesRule
range(5)0, 1, 2, 3, 4Starts at 0, stops before 5
range(2, 6)2, 3, 4, 5Start included, stop excluded
range(0, 10, 3)0, 3, 6, 9Third argument is the step
range(5, 0, -1)5, 4, 3, 2, 1Negative step counts down
for letter in "hey":
    print(letter)        # h, then e, then y

for i in range(3):
    print("Row", i)      # Row 0, Row 1, Row 2

range(5) runs the body exactly five times, which is why it is the standard way to repeat something a fixed number of times. The excluded stop value matches string slicing from the previous lesson: word[0:3] and range(0, 3) both mean positions 0, 1 and 2.

7. Tracing a loop by hand

The most useful skill in this lesson is not writing loops but predicting what one does, by tracking every variable on paper, line by line. That is called tracing.

total = 0
for i in range(1, 5):
    total = total + i
print(total)
Passitotal beforetotal after
1101
2213
3336
44610

The program prints 10. range(1, 5) stops before 5, so 5 is never added.

This is not a beginner's crutch. A study by Lister and colleagues, run across twelve universities in seven countries and published in the ACM SIGCSE Bulletin in 2004, found that many students finishing a first programming course could not reliably predict the output of short code like this. Their results suggested that being able to read and trace code comes before being able to write it.

In practice: When a loop surprises you, stop re-running it and trace it. A table with one column per variable finds most loop bugs in minutes.

8. Predict: a loop inside a loop

Loops can contain loops. The inner one runs completely on every pass of the outer one. Trace this before revealing the answer:

Predict first

What does this print?

count = 0
for i in range(3):
    for j in range(i):
        count += 1
print(count)

Nested loops are how programs walk through grids, tables and every pair of items in a list. The number of inner passes multiplies quickly: two loops of 1,000 each is a million repetitions, which is why it pays to know exactly how many times an inner loop runs.

9. break, continue, and choosing the right loop

Two statements change a loop's flow from inside. continue skips to the next pass; break leaves the loop entirely:

for word in ["apple", "", "banana", "stop", "cherry"]:
    if word == "":
        continue          # skip empty entries
    if word == "stop":
        break             # end the loop now
    print(word)

This prints apple and banana. The empty string is skipped, and cherry is never reached because break fires first.

forwhile
Use whenYou have a sequence or a known countYou repeat until a condition changes
Typical exampleEvery item in a list, range(10)Retry until valid input, grow until a target
EndsAutomatically, when items run outOnly when the condition becomes False or break runs
Main riskOff-by-one in range boundsInfinite loop if the condition never changes

When either would work, prefer for: it cannot run forever, and the reader sees the number of passes at a glance.

10. Putting it together: a number guessing game

Decisions and loops together are enough for a real interactive program:

secret = 42
attempts = 0

while True:
    guess = int(input("Guess a number from 1 to 100: "))
    attempts += 1
    if guess < secret:
        print("Too low")
    elif guess > secret:
        print("Too high")
    else:
        print(f"Correct in {attempts} attempts")
        break

Guessing 50, 25, then 42 prints Too high, Too low, Correct in 3 attempts.

while True looks like an infinite loop, and it would be without the break. It is the standard pattern when the exit condition is only known in the middle of the block: here, after the guess is read and checked. Everything else is from this lesson: a comparison chain with if, elif and else, a counter updated with +=, and input() converted with int() from the previous lesson.

Try it: Halving the range each time (50, then 25 or 75, and so on) finds any number from 1 to 100 in at most 7 guesses, because 2 to the 7th is 128. Play it that way, then add a rule that ends the game after 7 attempts.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. What does `list(range(2, 8, 2))` produce?
    • [2, 4, 6, 8]
    • [2, 4, 6]
    • [0, 2, 4, 6]
    • [2, 3, 4, 5, 6, 7]
  2. With `x = 15`, the chain `if x > 5: ... elif x > 10: ... else: ...` runs which branch?
    • The elif branch
    • Both the if and the elif branches
    • The else branch
    • The if branch
  3. Which loop is most likely to run forever by mistake?
    • A while loop whose body never changes the variables in its condition
    • A for loop over a list
    • A for loop over range(1000000)
    • A for loop that contains break
  4. `total = 0` then `for i in range(4): total += i`. What is `total` afterwards?
    • 10
    • 4
    • 6
    • 3
  5. What is the value of `(3 > 2) and not (5 == 5)`?
    • True
    • False
    • 5
    • It raises an error

Related lessons