Conditionals — if/elif/else & match — Concept Check
Questions on Conditionals — if/elif/else & match. Branching in Python is if/elif/else (there is no switch keyword) — plus structural pattern matching with match/case since Python 3.10 for elegant multi-shape logic.
Questions in this quiz
8 questions on Conditionals — if/elif/else & match — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.A function processes orders and uses guard clauses to handle different scenarios. What is the benefit of using guard clauses in this context?
- AIt ensures that all conditions are evaluated before returning.
- BIt makes the code run faster by skipping unnecessary checks.
- CIt allows multiple conditions to be checked simultaneously.
- DIt reduces the complexity by avoiding deep nesting.
2.You have a list of commands to process with a match/case statement in Python 3.10. What happens if a command doesn't match any case?
- AThe default case is executed.
- BAn error is raised.
- CThe last matched case is re-executed.
- DThe program continues without action.
3.Consider a function using if/elif/else to determine grades. What is a key advantage of using elif chains over deeply nested if statements?
- AElif chains can handle more conditions than nested ifs.
- BThey automatically catch logical errors in conditions.
- CElif chains are faster than nested if statements.
- DThey make the code more readable and maintainable.
4.A Python function uses match/case to handle API events. How does match/case improve handling over traditional if/elif/else?
- AIt can destructure and bind variables in patterns.
- BIt evaluates conditions faster than if/elif/else.
- CIt automatically optimizes the order of conditions.
- DIt allows for more concise and readable code.
5.A developer uses match/case to process commands. What will the case ['pick', *items] do when given the command 'pick apple orange'?
- AIt will bind 'apple' and 'orange' to 'items'.
- BIt will throw an error due to multiple items.
- CIt will ignore the command as invalid.
- DIt will only bind 'apple' to 'items'.
6.A Python script uses if/elif/else to check payment status. What is a common mistake to avoid when using truthiness in conditions?
- ARelying on None as a truthy value.
- BExpecting empty collections to be True.
- CUsing == to compare boolean expressions.
- DAssuming all non-zero values are True.
7.What will the function handle('quit') return when using match/case for command processing?
- A'bye'
- B'quitting'
- C'unknown command'
- D'exit'
8.In Python 3.10, what is the purpose of the underscore (_) in match/case statements?
- ATo match any single character.
- BTo bind unmatched variables.
- CTo act as a wildcard matching any pattern.
- DTo indicate a syntax error.