Skip to content
Laviyx Learn

Try

Python Conditions Practice

Practise if, elif and else, combined and nested conditions, and controlling loops with break, continue and pass.

Beginner8 problemsUpdated

Review first: if, if else, elif, Nested Conditions, break, continue, pass

  1. 1.Marks to grades

    Beginner

    For each mark in marks = [95, 82, 67, 45, 74], print the mark and its grade:

    • 90 and above: A
    • 75 to 89: B
    • 60 to 74: C
    • below 60: F
    Show hint

    Use if / elif / else and check from the highest grade down, so each check only needs a lower limit.

    Show solution
    Python
    marks = [95, 82, 67, 45, 74]
    
    for mark in marks:
        if mark >= 90:
            grade = "A"
        elif mark >= 75:
            grade = "B"
        elif mark >= 60:
            grade = "C"
        else:
            grade = "F"
        print(mark, grade)
    Output
    95 A
    82 B
    67 C
    45 F
    74 C

    Because elif branches are checked in order and only the first true one runs, elif mark >= 75 already knows the mark is below 90.

  2. 2.Leap years

    Beginner

    A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap years only if they are also divisible by 400. For each year in [1900, 2000, 2024, 2026], print whether it is a leap year.

    Show hint

    Combine the rules with and and or: (year % 4 == 0 and year % 100 != 0) or year % 400 == 0.

    Show solution
    Python
    for year in [1900, 2000, 2024, 2026]:
        is_leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
        if is_leap:
            print(year, "is a leap year")
        else:
            print(year, "is not a leap year")
    Output
    1900 is not a leap year
    2000 is a leap year
    2024 is a leap year
    2026 is not a leap year

    The standard library already knows this rule, import calendar then calendar.isleap(year), which is what you should use in real code.

  3. 3.Cinema ticket price

    Beginner

    Tickets cost 250. Children under 12 pay 120. Everyone else aged under 25 pays 180 if they are a student. Write a function ticket_price(age, is_student) and print the price for (8, False), (19, True), (19, False) and (40, True).

    Show hint

    Check the child case first. Inside the else branch, check the student discount.

    Show solution
    Python
    def ticket_price(age, is_student):
        if age < 12:
            return 120
        else:
            if age < 25 and is_student:
                return 180
            return 250
    
    
    for age, student in [(8, False), (19, True), (19, False), (40, True)]:
        print(age, student, ticket_price(age, student))
    Output
    8 False 120
    19 True 180
    19 False 250
    40 True 250

    The nested if can be flattened with elif age < 25 and is_student:. Both versions are correct; flatter code is usually easier to read.

  4. 4.Find the first negative number

    Beginner

    Loop over readings = [12, 7, 0, -3, 8, -1] and print the first negative reading and its position, then stop. If there is no negative reading, print All readings are fine.

    Show hint

    Use break to stop the loop. A for ... else block runs only when the loop was not stopped by break.

    Show solution
    Python
    readings = [12, 7, 0, -3, 8, -1]
    
    for i, value in enumerate(readings):
        if value < 0:
            print(f"First negative reading: {value} at position {i}")
            break
    else:
        print("All readings are fine")
    Output
    First negative reading: -3 at position 3
  5. 5.Skip the blanks

    Beginner

    Print a greeting for every name in names = ["Asha", "", "Ravi", " ", "Meera"], skipping names that are empty or only spaces.

    Show hint

    name.strip() removes spaces; an empty string is falsy. Use continue to skip to the next name.

    Show solution
    Python
    names = ["Asha", "", "Ravi", "   ", "Meera"]
    
    for name in names:
        if not name.strip():
            continue
        print(f"Hello, {name}!")
    Output
    Hello, Asha!
    Hello, Ravi!
    Hello, Meera!
  6. 6.Check a password

    Beginner

    A password is strong when it has at least 8 characters, at least one digit, and at least one uppercase letter. For each password in ["sunshine", "Sunshine1", "Ab1"], print strong or the first rule it breaks.

    Show hint

    any(ch.isdigit() for ch in password) is True if at least one character is a digit.

    Show solution
    Python
    def check(password):
        if len(password) < 8:
            return "too short"
        elif not any(ch.isdigit() for ch in password):
            return "needs a digit"
        elif not any(ch.isupper() for ch in password):
            return "needs an uppercase letter"
        else:
            return "strong"
    
    
    for pw in ["sunshine", "Sunshine1", "Ab1"]:
        print(pw, "->", check(pw))
    Output
    sunshine -> needs a digit
    Sunshine1 -> strong
    Ab1 -> too short
  7. 7.FizzBuzz

    Beginner

    Print the numbers 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of 5, and FizzBuzz for multiples of both. Print them on one line separated by spaces.

    Show hint

    Check "multiple of both" (divisible by 15) first, otherwise the multiple-of-3 branch catches 15.

    Show solution
    Python
    results = []
    
    for n in range(1, 16):
        if n % 15 == 0:
            results.append("FizzBuzz")
        elif n % 3 == 0:
            results.append("Fizz")
        elif n % 5 == 0:
            results.append("Buzz")
        else:
            results.append(str(n))
    
    print(" ".join(results))
    Output
    1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
  8. 8.Plan first with pass

    Beginner

    Write a function process(order) that will later handle three statuses. For now, only "new" orders should print Processing new order. Leave branches for "paid" and "shipped" that do nothing yet, then call it with "new", "paid" and "shipped".

    Show hint

    A block cannot be empty in Python. pass is a statement that does nothing.

    Show solution
    Python
    def process(order):
        if order == "new":
            print("Processing new order")
        elif order == "paid":
            pass  # TODO: send receipt
        elif order == "shipped":
            pass  # TODO: send tracking link
    
    
    for status in ["new", "paid", "shipped"]:
        process(status)
    print("Done")
    Output
    Processing new order
    Done

    Without pass, Python raises an IndentationError because the elif blocks have no statements. A # TODO comment makes the unfinished work easy to find later.