16. Selection (If Statements)
True or False (a Boolean value).if statement, alongside comparison operators to test conditions.if block.# Basic selection in Python
age = 15
if age >= 12:
print("You are eligible for a student ticket!")
16.1. Comparison and Logical Operators
To create conditional expressions for selection, Python relies on comparison and logical operators:
Comparison Operators: Used to compare two values:
==(equals),!=(not equals),>(greater than),<(less than),>=(greater than or equal to),<=(less than or equal to).Logical Operators: Used to combine multiple conditions:
and(both True),or(at least one True),not(reverses True/False).
# Using comparison and logical operators
score = 85
has_pass = True
if score >= 80 and has_pass:
print("You passed with distinction!")
16.1.1. Quiz: Comparison Operators and Basic If
16.1.1.1. Fill-in-the-Blanks (Cloze)
1. Making decisions in a program based on conditions is called Drop here.
2. An expression that evaluates to either True or False is called a Drop here expression.
3. The comparison operator used to test if two values are equal is Drop here.
4. Python uses Drop here (4 spaces) to specify the block of code inside an if statement.
5. The logical operator Drop here requires both conditions to be True for the overall statement to evaluate to True.
16.1.1.2. Code Ordering Examples
Example 1: Check if a temperature is greater than 30 degrees and print a warning message.
Example 2: Combine two conditions using the and operator to verify login status.
Example 3: Use the != operator to test for unequal values.
16.1.1.3. Multiple Choice Questions
Which operator is used to check if two values are equal in an if condition?
Correct! The double equals sign == checks for equality.
Incorrect. The single equals sign = is used for variable assignment.
Incorrect. != checks if two values are NOT equal.
Incorrect. := is the walrus operator, not the equality comparison operator.
What happens in Python if you forget to indent the line directly following an if statement?
Correct! Python strictly requires indented blocks after conditional statements.
Incorrect. Python cannot parse unindented code blocks following an if statement.
Incorrect. Syntax and indentation rules are strictly enforced by the interpreter.
Incorrect. Indentation errors prevent code execution.
Given x = 10, what does x > 5 and x < 15 evaluate to?
Correct! Both 10 > 5 (True) and 10 < 15 (True) are True, so the combined statement is True.
Incorrect. Since both conditions are satisfied, the and expression evaluates to True.
Incorrect. Logical comparisons always yield Boolean True or False.
Incorrect. The expression is valid Python syntax.
Which symbol is placed at the end of an if line in Python?
Correct! A colon : must follow the condition in an if statement.
Incorrect. Colons : are used in Python conditional headers rather than semicolons.
Incorrect. Colons indicate the start of an indented block.
Incorrect. Python uses colons and indentation rather than curly braces.
What will print(5 != 5) output?
Correct! 5 is equal to 5, so the ‘not equal to’ check yields False.
Incorrect. 5 is equal to 5, so 5 != 5 is False.
Incorrect. != is valid syntax.
Incorrect. Logical checks return a Boolean value.
Which logical operator reverses a Boolean value (turning True to False, and False to True)?
Correct! The not operator negates any Boolean expression.
Incorrect. and joins two expressions together.
Incorrect. or evaluates if at least one condition is True.
Incorrect. flip is not a valid Python operator keyword.
What is the outcome of True or False in Python?
Correct! An or statement evaluates to True if at least one side is True.
Incorrect. At least one side is True, so or yields True.
Incorrect. Logical operators evaluate to Boolean results.
Incorrect. Valid logical expression.
What does the operator <= test?
Correct! <= tests whether the left value is smaller than or equal to the right value.
Incorrect. Greater than or equal to is represented as >=.
Incorrect. Strictly less than uses <.
Incorrect. Not equal to uses !=.
Given a = 3 and b = 7, which condition evaluates to True?
Correct! 3 is strictly less than 7.
Incorrect. 3 is not greater than 7.
Incorrect. 3 is not equal to 7.
Incorrect. 3 is not greater than or equal to 7.
What value type does a conditional check evaluate to?
Correct! Conditions evaluate to True or False, which are Boolean values.
Incorrect. Strings store text values.
Incorrect. Integers represent whole numbers.
Incorrect. Floats represent decimal numbers.
16.2. The Else Statement
An else statement provides an alternative path in code execution:
Fallback Execution: The code inside an
elseblock runs only when the precedingifcondition evaluates toFalse.Syntax: The
else:keyword must align vertically with its correspondingifstatement and be followed by a colon.Binary Decision Making:
if-elsecreates a two-way choice (either the condition is met, or the alternative happens).
# Using if-else for two-way selection
password = "secret"
user_input = "12345"
if user_input == password:
print("Access Granted")
else:
print("Access Denied: Incorrect Password")
16.2.1. Quiz: The Else Statement
16.2.1.1. Fill-in-the-Blanks (Cloze)
1. An Drop here block executes when the preceding condition evaluates to False.
2. An else statement does not accept a condition; it simply uses the Drop here syntax.
3. Selection structures with both if and else handle Drop here or two-way choices.
4. The else statement must match the Drop here level of its corresponding if statement.
5. Code inside an else block must be Drop here to show membership in that block.
16.2.1.2. Code Ordering Examples
Example 1: Check if a number is positive or non-positive using if-else.
Example 2: Determine passing status based on score threshold.
Example 3: Check item stock availability.
16.2.1.3. Multiple Choice Questions
When does code inside an else block execute?
Correct! The else block acts as a fallback when conditions fail.
Incorrect. True conditions run the if block, bypassing else.
Incorrect. Else blocks execution depends on condition failure.
Incorrect. Else handles runtime logic branches.
Which of the following syntax structures for an else statement is correct?
Correct! else is followed by a colon and an indented code block below.
Incorrect. else statements do not take explicit condition arguments.
Incorrect. then is not a keyword in Python syntax.
Incorrect. Statements end with colons rather than semicolons.
Given age = 10, what will execute in if age >= 18: print("Adult") else: print("Child")?
Correct! 10 >= 18 is False, triggering the else block.
Incorrect. The condition fails, so “Adult” is skipped.
Incorrect. Only one path executes in if-else.
Incorrect. The else branch executes and prints “Child”.
Can an else block exist in Python without a preceding if statement?
Correct! Unattached else statements raise SyntaxError.
Incorrect. Else requires a preceding control structure.
Incorrect. Else requires context.
Incorrect. Else requires an accompanying conditional.
What is output by is_logged = False; if is_logged: print("In") else: print("Out")?
Correct! is_logged is False, directing execution to the else block.
Incorrect. Condition evaluates to False.
Incorrect. Output is produced by the print in the else block.
Incorrect. The structure is valid.
How many paths in an if-else block can be executed during a single run?
Correct! Either the if block executes OR the else block executes.
Incorrect. If and else are mutually exclusive.
Incorrect. Exactly one path will be taken.
Incorrect. Standard if-else offers two branches.
What error occurs if else: is indented further right than its matching if: statement?
Correct! Else must align with its paired if statement.
Incorrect. NameErrors relate to unassigned identifiers.
Incorrect. TypeErrors involve incompatible types.
Incorrect. ValueErrors stem from invalid argument values.
What will happen in x = 5; if x == 5: print("A") else: print("B")?
Correct! Condition 5 == 5 is True, so the if block runs and else is skipped.
Incorrect. The condition is True, so else does not run.
Incorrect. Only one branch executes.
Incorrect. “A” is output.
Why does else x > 10: raise a SyntaxError in Python?
Correct! Use elif when testing additional conditions.
Incorrect. Integers are valid in condition expressions.
Incorrect. > is a valid comparison operator.
Incorrect. Keywords must be lowercase in Python.
What is the primary role of an else branch?
Correct! Else acts as the catch-all branch.
Incorrect. Loops handle repetition.
Incorrect. Variables can be assigned in any branch.
Incorrect. Else manages conditional branching.
16.3. Multi-Branch Selection with Elif
When you need to test multiple conditions in sequence, use elif (short for else if):
Sequential Evaluation: Python checks conditions from top to bottom. The first condition that evaluates to
Trueruns its block, and all remainingelifandelsebranches are skipped!Multiple Conditions: You can chain as many
elifblocks as necessary.Optional Else: An
elseblock can be placed at the end as a final catch-all branch.
# Multi-branch selection with if-elif-else
score = 75
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Grade:", grade)
16.3.1. Quiz: Multi-Branch Selection with Elif
16.3.1.1. Fill-in-the-Blanks (Cloze)
1. The keyword Drop here is short for "else if" in Python syntax.
2. In an if-elif-else chain, Python stops testing conditions as soon as it finds the Drop here True expression.
3. An optional Drop here statement can be placed at the end of an if-elif chain to handle all unmatched cases.
4. You can include Drop here elif statements within a single selection structure.
5. Order matters in elif chains because expressions are evaluated Drop here from top to bottom.
16.3.1.2. Code Ordering Examples
Example 1: Assign a descriptive label based on speed evaluation.
Example 2: Determine ticket pricing based on age category.
Example 3: Categorize temperature into hot, warm, or cold.
16.3.1.3. Multiple Choice Questions
What does elif stand for in Python?
Correct! elif is a contraction of else if.
Incorrect. elif stands for else if.
Incorrect. elif is used exclusively for conditional branching.
Incorrect. elif stands for else if.
What will be output by the following code? x = 15; if x > 20: print("A") elif x > 10: print("B") elif x > 5: print("C") else: print("D")
Correct! x > 20 is False, but x > 10 is True. Output is “B”, and remaining branches are skipped.
Incorrect. Only the first matching branch executes.
Incorrect. 15 is not greater than 20.
Incorrect. 15 > 10 evaluated to True, so else does not run.
How many elif blocks can be included inside a single selection structure?
Correct! You can add unlimited elif statements between if and else.
Incorrect. Multiple elif blocks are permitted.
Incorrect. There is no artificial cap on elif count.
Incorrect. While optional, when used, count is unlimited.
Why is the order of conditions important in an if-elif-else chain?
Correct! Subsequent conditions are skipped once a match is found.
Incorrect. Python evaluates top to bottom.
Incorrect. Order affects logic, not syntax validity.
Incorrect. Conditions are tested sequentially.
Given score = 95, why would if score >= 60: print("Pass") elif score >= 90: print("Excellent") be considered logically flawed?
Correct! Specific conditions should precede broader conditions.
Incorrect. Python handles numeric comparisons cleanly.
Incorrect. Strings are standard arguments for print().
Incorrect. Elif correctly follows if.
In an if-elif-else structure, is the final else block required?
Correct! You can write if-elif chains without a trailing else.
Incorrect. Else is completely optional.
Incorrect. Optional regardless of elif count.
Incorrect. Execution continues past the chain normally.
What is output by val = 0; if val > 0: print("Pos") elif val < 0: print("Neg") else: print("Zero")?
Correct! 0 > 0 is False, 0 < 0 is False, so execution lands in else.
Incorrect. 0 is not strictly greater than 0.
Incorrect. 0 is not strictly less than 0.
Incorrect. The structure is valid.
What happens if none of the conditions in an if-elif structure (without an else) evaluate to True?
Correct! The entire selection block is bypassed cleanly.
Incorrect. No error occurs when conditions evaluate to False.
Incorrect. Conditions must evaluate to True to execute.
Incorrect. Execution proceeds past the block.
Which statement about conditional evaluation is TRUE?
Correct! Evaluation short-circuits on first match.
Incorrect. Execution skips remaining branches.
Incorrect. Conditions are tested top to bottom.
Incorrect. Execution begins at the initial if.
Given x = 10, what does if x == 5: print("Five") elif x == 10: print("Ten") else: print("Other") output?
Correct! First condition is False, second condition evaluates to True.
Incorrect. 10 == 5 is False.
Incorrect. The elif branch matches, so else is bypassed.
Incorrect. Only one branch executes.
16.4. Nested Selection Structures
You can place an if statement inside another if statement. This is called nested selection:
Hierarchical Logic: Used when a second condition only needs to be checked if a primary condition passes.
Indentation Levels: Each nested level requires an additional 4 spaces of indentation.
# Nested selection example
age = 16
has_permission = True
if age < 18:
if has_permission:
print("Allowed with parental consent.")
else:
print("Not allowed without consent.")
else:
print("Allowed independently.")
16.4.1. Quiz: Nested Selection Structures
16.4.1.1. Fill-in-the-Blanks (Cloze)
1. Placing an if statement inside another if statement is called Drop here selection.
2. Each inner level of nested selection requires additional Drop here.
3. In a nested structure, inner conditions are evaluated only if the outer condition is Drop here.
4. Complex nested selection can often be simplified using Drop here operators like `and`.
5. An inner else block attaches to the closest preceding Drop here statement at the same indentation level.
16.4.1.2. Code Ordering Examples
Example 1: Check membership status and apply discount if active.
Example 2: Check user age and driving test status.
Example 3: Check weather conditions for outdoor activity.
16.4.1.3. Multiple Choice Questions
What is nested selection in Python?
Correct! Nesting involves placing control structures inside existing blocks.
Incorrect. Statements cannot be assigned inside variables.
Incorrect. Logical operators combine conditions in single statements.
Incorrect. Nesting specifically refers to hierarchical block structures.
Given a = True and b = False, what prints in if a: if b: print("1") else: print("2")?
Correct! Outer condition a is True, so execution enters the inner block. Inner condition b is False, executing inner else.
Incorrect. Inner condition b is False.
Incorrect. Inner else executes and outputs “2”.
Incorrect. Only one inner branch executes.
How is indentation handled for a nested if block?
Correct! Each nested layer adds 4 indentation spaces.
Incorrect. All nested statements require indentation.
Incorrect. Python prohibits mixing tabs and spaces.
Incorrect. Standard Python style uses 4 spaces per nesting level.
What happens if the outer condition of a nested if statement evaluates to False?
Correct! Execution proceeds past the outer block.
Incorrect. Outer condition failure bypasses nested contents.
Incorrect. Bypassing conditions is standard control flow behavior.
Incorrect. Inner branches are unreachable if outer condition fails.
Which single if statement is equivalent to: if x > 0: if y > 0: print("Both positive")?
Correct! Nested if checks without alternative branches match logical and conditions.
Incorrect. or allows execution when only one condition passes.
Incorrect. not negates the condition.
Incorrect. Equality check differs from positive check.
Given x = 5 and y = -2, what outputs in if x > 0: if y > 0: print("A") else: print("B") else: print("C")?
Correct! Outer condition x > 0 is True. Inner condition y > 0 is False, triggering inner else (“B”).
Incorrect. y > 0 is False.
Incorrect. Outer condition was True, so outer else is skipped.
Incorrect. “B” prints.
Why might a programmer choose logical operators over deep nesting?
Correct! Deep nesting creates hard-to-read “pyramid” code structures.
Incorrect. Python allows multiple nesting levels.
Incorrect. Primary benefit is readability and maintenance.
Incorrect. Nesting is valid syntax without memory issues.
To which if statement does an else block attach in nested selection?
Correct! Indentation defines statement binding.
Incorrect. Indentation matches else to its specific level.
Incorrect. Binding is scoped strictly by indentation level.
Incorrect. Else attaches to a single corresponding statement.
What output is produced by p = False; q = True; if p: if q: print("X") else: print("Y")?
Correct! p is False, so outer condition fails and inner statements are bypassed.
Incorrect. Outer condition p is False.
Incorrect. Outer block is completely skipped.
Incorrect. Syntax is valid.
What does excessive levels of nesting (deep nesting) make difficult?
Correct! Deep nesting reduces legibility and increases logic bug risk.
Incorrect. Variables function identically regardless of depth.
Incorrect. Math operations are unaffected by nesting depth.
Incorrect. Nesting affects code structure rather than installation.