BeginnerPython · Lesson 3 of 8

Decisions & Loops

if / elif / else, comparison and logical operators, for loops with range, and while.

Python uses indentation (4 spaces) to group code — there are no braces. if, elif and else choose between branches; combine conditions with and, or and not.

A for loop walks through any sequence: a list, a string, or range(start, stop). enumerate() gives you the position and the item together.

A while loop repeats until its condition becomes false. break leaves a loop early; continue skips to the next round.

grades.pyPython
def grade_for(score):
    if score >= 75:
        return "A"
    elif score >= 65:
        return "B"
    elif score >= 45:
        return "C"
    elif score >= 30:
        return "D"
    else:
        return "F"


scores = [82, 67, 49, 31, 18]

for i, score in enumerate(scores, start=1):
    grade = grade_for(score)
    status = "pass" if grade != "F" else "fail"
    print(f"Student {i}: {score} -> {grade} ({status})")

for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)

countdown = 3
while countdown > 0:
    print(f"Starting in {countdown}...")
    countdown -= 1
Runs in your browser · Python

Key points

  • Indentation is syntax in Python — keep it consistent (4 spaces).
  • for item in sequence is the normal loop; range() makes number sequences.
  • x if condition else y picks a value in one line.

Exercise

Print the multiplication table for a number from 1 to 12. Then write a guessing game: pick a secret number, keep asking the user with while until they guess it, and print "higher" or "lower" hints.

Show solution

Try the exercise yourself first — then compare your approach with this one.

The multiplication table is a for loop over range(1, 13). The guessing game keeps asking inside a while loop until the guess is right, giving a hint each time.

tables.pyPython
import random

number = int(input("Times table for: "))
for i in range(1, 13):
    print(f"{i:>2} x {number} = {i * number}")

secret = random.randint(1, 100)
guesses = 0
guess = None
while guess != secret:
    guess = int(input("Guess the number (1-100): "))
    guesses += 1
    if guess < secret:
        print("Higher!")
    elif guess > secret:
        print("Lower!")
print(f"Correct! You needed {guesses} guesses.")
Runs in your browser · Python

Check your understanding

  1. Which numbers does range(1, 5) produce?

  2. How does Python know which lines belong inside an if block?

  3. What does enumerate(scores, start=1) give you on each loop?

  4. What does continue do inside a loop?

Ask AI