Conditionals

Computer Science · Python

Question 1 of 10

0

    What does this Python code print? n = 4 if n >= 47: print(49) elif n >= 24: print(77) else: print(82)

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Conditionals explained

    Conditionals let a program choose which code to run depending on whether a condition is true. In Python they are written with if, elif and else, and each block is marked by indentation rather than by braces.

    An if statement runs its block only when its condition is true. An optional elif checks another condition when the earlier ones are false, and else runs when none of the conditions matched. Python checks the conditions in order and runs only the first block whose condition is true.

    Conditions usually use comparison operators such as ==, !=, <, >, <= and >=. The logical operators and, or and not combine them. Python also uses truthiness: values such as an empty list, an empty string and 0 count as False in a condition.

    Indentation is part of the syntax. Each block must be indented consistently under its if, elif or else line, and a mistake raises an IndentationError.

    A short form, the conditional expression, picks one of two values: label = "pass" if score >= 50 else "fail".

    Worked example

    def grade(score):
        if score >= 90:
            return "A"
        elif score >= 80:
            return "B"
        else:
            return "C"
    
    print(grade(84))
    
    1. The first test, 84≥9084 \ge 90, is false.
    2. The second test, 84≥8084 \ge 80, is true, so the function returns "B".

    Order matters. If the test for 80 came first, a score of 95 would match it and be graded B, so the most specific test goes first.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this Python code print? n = 94 if n >= 36: print(15) elif n >= 14: print(59) else: print(22)

    • Medium

      What does this Python code print? x = 7 y = 0 if x > 3 and y < 6: result = x - y elif x > 3 or y < 6: result = y - x else: result = 0 print(result)

    • Hard

      What does this Python code print? v = 4 lo = 4 hi = 8 if lo < v < hi: result = v or 99 else: result = lo and hi print(result)