Python conditionals exercises solutions cheat sheet if elif else

Python conditionals exercises — 4 solved with solutions and cheat sheet

Python conditionals exercises with solutions are the best way to cement if, elif and else. You’ve seen the theory and practised with real programs. Now it’s time to solve on your own.

In this article you’ll find four exercises across three levels of difficulty, with special attention to the mistake of confusing and with or — one of the trickiest in FP1.

As always: try to solve it, use the hint if you’ve been stuck for more than 10 minutes, and compare with the commented solution at the end. You can also step through the code in pythontutor.com to see it running line by line.

How to use this article

Read the exercise → try to solve it → if you’re not making progress, read the hint → compare your solution. Don’t jump straight to the solutions — you learn twice as much by solving it yourself.

These Python conditionals exercises are designed so you come out knowing how to apply them in any situation.


Basic Level

Exercise 1 — Movie rating system

Write a program that asks for the user’s age and a movie rating, and determines whether they can watch it. The ratings are: G (all ages), PG (parental guidance recommended for under 10s), PG-13 (not recommended for under 13), R (not recommended for under 17), NC-17 (18+ only).

The output should look like this:

Age: 15
Movie rating: R

--- Result ---
Rating R: not recommended for under 17s
Your age: 15
Access: ✗ You cannot watch this film without an adult

💡 Hint: Use elif for each rating from most to least restrictive. The classic and/or mistake appears here — for example “older than 13 AND younger than 17” needs and. Using or would mean any age passes since any number is either ≥13 or <17. Remember: and means both conditions must be true at the same time, or means just one needs to be true.


Exercise 2 — Income tax calculator

Ask for the annual gross salary and calculate the tax owed using these simplified brackets:

Up to €12,450         → 19%
€12,450 to €20,200    → 24%
€20,200 to €35,200    → 30%
€35,200 to €60,000    → 37%
Over €60,000          → 45%

The output should look like this:

Annual gross salary (€): 28000

--- Income tax calculation ---
Gross salary:          28000.0 €
Tax bracket:           30%
Tax:                   8400.0 €
Net salary:            19600.0 €
Monthly net salary:    1633.33 €

💡 Hint: This is a simplified bracket system — apply the percentage to the whole salary, not just the part within the bracket. The typical error here is the elif order, if you put the 45% bracket before the 37% one, all high salaries will fall into 45% even when they should be 37%. Always order from lowest to highest salary.


Intermediate Level

Exercise 3 — Password strength validator

Write a program that asks for a password and evaluates its security based on these criteria, showing which ones it meets and which it doesn’t:

8+ characters          → +1 point
Contains uppercase     → +1 point
Contains lowercase     → +1 point
Contains numbers       → +1 point
Contains special chars (!@#$%^&*) → +1 point

Final classification: 0-2 points = Very weak, 3 = Weak, 4 = Strong, 5 = Very strong.

Password: Python@2024

--- Password analysis ---
✓ Long enough (10 characters)
✓ Contains uppercase
✓ Contains lowercase
✓ Contains numbers
✓ Contains special characters

Score: 5/5
Strength: Very strong 🔒

💡 Hint: Use any() with a generator expression to check each criterion, for example any(c.isupper() for c in password) checks if any character is uppercase. The and/or error appears if you try to combine criteria: “has uppercase AND lowercase” needs and — these are two separate requirements that both need to be true simultaneously. “has uppercase OR lowercase” would only require one of them, which is a completely different check.


Final Challenge

Exercise 4 — Number guessing game

The classic. Write a program that generates a random number between 1 and 100 and lets the player guess it. The program should give “too high” or “too low” hints and keep track of attempts. At the end, show how many attempts were needed and rate the performance.

=== GUESS THE NUMBER ===
I'm thinking of a number between 1 and 100...

Attempt 1 — Your guess: 50
→ Too low

Attempt 2 — Your guess: 75
→ Too high

Attempt 3 — Your guess: 63
→ Too low

Attempt 4 — Your guess: 69
→ Correct! 🎉

--- Result ---
You guessed in 4 attempts
Rating: Great 👏

Rating by attempts: 1-3 = Incredible, 4-6 = Great, 7-10 = Good, more than 10 = Keep practising.

💡 Hints:

  • Import random at the top: import random and generate with random.randint(1, 100)
  • Use a while loop to repeat until correct — we’ll cover loops in depth next topic, but for this exercise it works like this: while not guessed: and when they get it right set guessed = True
  • The and/or error in the rating: “between 4 and 6 attempts” is attempts >= 4 and attempts <= 6 — NOT or. With or every number would pass since any number is either ≥4 or ≤6

Commented solutions

Solution Exercise 1:

# Movie rating system
age = int(input("Age: "))
rating = input("Movie rating: ").upper()

restrictions = {
    "G":     (0,  "all ages"),
    "PG":    (10, "parental guidance recommended for under 10s"),
    "PG-13": (13, "not recommended for under 13s"),
    "R":     (17, "not recommended for under 17s"),
    "NC-17": (18, "18+ only")
}

print(f"\n--- Result ---")

if rating not in restrictions:
    print("Rating not recognised")
else:
    min_age, description = restrictions[rating]
    print(f"Rating {rating}: {description}")
    print(f"Your age: {age}")

    if age >= min_age:
        print("Access: ✓ You can watch this film")
    else:
        print("Access: ✗ You cannot watch this film without an adult")

Solution Exercise 2:

# Income tax calculator
salary = float(input("Annual gross salary (€): "))

if salary <= 12450:
    bracket = 19
elif salary <= 20200:
    bracket = 24
elif salary <= 35200:
    bracket = 30
elif salary <= 60000:
    bracket = 37
else:
    bracket = 45

tax = round(salary * bracket / 100, 2)
net = round(salary - tax, 2)
monthly = round(net / 12, 2)

print(f"\n--- Income tax calculation ---")
print(f"Gross salary:       {salary} €")
print(f"Tax bracket:        {bracket}%")
print(f"Tax:                {tax} €")
print(f"Net salary:         {net} €")
print(f"Monthly net salary: {monthly} €")

Solution Exercise 3:

# Password strength validator
password = input("Password: ")
specials = "!@#$%^&*"
score = 0

print(f"\n--- Password analysis ---")

if len(password) >= 8:
    print(f"✓ Long enough ({len(password)} characters)")
    score += 1
else:
    print(f"✗ Too short ({len(password)} characters, minimum 8)")

if any(c.isupper() for c in password):
    print("✓ Contains uppercase")
    score += 1
else:
    print("✗ No uppercase letters")

if any(c.islower() for c in password):
    print("✓ Contains lowercase")
    score += 1
else:
    print("✗ No lowercase letters")

if any(c.isdigit() for c in password):
    print("✓ Contains numbers")
    score += 1
else:
    print("✗ No numbers")

if any(c in specials for c in password):
    print("✓ Contains special characters")
    score += 1
else:
    print("✗ No special characters")

if score <= 2:
    strength = "Very weak 🔓"
elif score == 3:
    strength = "Weak 🔐"
elif score == 4:
    strength = "Strong 🔒"
else:
    strength = "Very strong 🔒"

print(f"\nScore: {score}/5")
print(f"Strength: {strength}")

Solution Exercise 4:

# Number guessing game
import random

secret = random.randint(1, 100)
attempts = 0
guessed = False

print("=== GUESS THE NUMBER ===")
print("I'm thinking of a number between 1 and 100...\n")

while not guessed:
    attempts += 1
    guess = int(input(f"Attempt {attempts} — Your guess: "))

    if guess < secret:
        print("→ Too low\n")
    elif guess > secret:
        print("→ Too high\n")
    else:
        print("→ Correct! 🎉")
        guessed = True

print(f"\n--- Result ---")
print(f"You guessed in {attempts} attempts")

if attempts <= 3:
    print("Rating: Incredible 🏆")
elif attempts <= 6:
    print("Rating: Great 👏")
elif attempts <= 10:
    print("Rating: Good ✓")
else:
    print("Rating: Keep practising 💪")

Cheat sheet — Python conditionals

# ============================================
# CHEAT SHEET — Python Conditionals
# Sergio Learns · sergiolearns.com
# ============================================

# BASIC STRUCTURE
if condition:
    # runs if condition is True
elif other_condition:
    # runs if other_condition is True
else:
    # runs if no condition is True

# MANDATORY RULES
# 1. Colon : at end of every if/elif/else — always required
# 2. 4-space indentation — always required
# 3. elif order matters — most restrictive (highest value) first

# COMPARISON OPERATORS
x == 5      # equal (DOUBLE ==, never single =)
x != 5      # not equal
x > 5       # greater than
x < 5       # less than
x >= 5      # greater or equal
x <= 5      # less or equal

# = assigns, == compares — never mix them
x = 5       # assignment — stores the value
x == 5      # comparison — returns True or False

# LOGICAL OPERATORS
x > 3 and x < 10    # BOTH must be True → True only if 3 < x < 10
x < 3 or x > 10     # at least ONE must be True
not (x > 5)         # inverts → True if x <= 5

# AND vs OR — the most common mistake
# AND: BOTH conditions must be met at the same time
age >= 18 and has_licence   # 18+ AND has licence
grade >= 5 and attendance >= 75  # passed AND attended enough

# OR: just ONE condition needs to be met
is_student or is_retired    # student OR retired
day == "Saturday" or day == "Sunday"  # is weekend

# TERNARY OPERATOR — if/else in one line
result = "Passed" if grade >= 5 else "Failed"
tier = "VIP" if spend >= 1000 else "Standard"

# MOST USED FP1 PATTERN — classify and store in variable
if value >= 9:
    category = "Outstanding"
elif value >= 7:
    category = "Good"
elif value >= 5:
    category = "Passed"
else:
    category = "Failed"
# then use category in the rest of the program

# MEMBERSHIP CHECK
if "@" in email:           # @ is in the string
if "a" not in word:        # a is NOT in the string
if rating in ["G", "PG"]:  # rating is one of these values

# CHECKING WITH any()
any(c.isupper() for c in text)    # any uppercase character?
any(c.isdigit() for c in text)    # any digit?
any(c in "!@#$" for c in text)    # any special character?

# COMMON ERRORS AND FIXES
# 1. Missing :       → SyntaxError: expected ':'
if x > 5:           # correct
if x > 5            # SyntaxError

# 2. Wrong indentation → IndentationError
if x > 5:
    print("yes")    # correct — 4 spaces
  print("yes")      # IndentationError — wrong spaces

# 3. = instead of == → SyntaxError
if x == 5:          # correct — comparison
if x = 5:           # SyntaxError — assignment in if

# 4. Wrong elif order → silent error (no message, wrong output)
# Always from most restrictive to least restrictive

# 5. and/or confusion → silent error
# "between 4 and 6": attempts >= 4 and attempts <= 6  ← correct
# "between 4 and 6": attempts >= 4 or attempts <= 6   ← wrong (always True)

Similar Posts

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *