What does a Python `if` statement do?
An `if` statement executes its indented block only when its condition evaluates to true.
Study 3 Conditional Control Flow with 12 free online flashcards. Review key terms, definitions, and concepts with this interactive flashcard deck.
What does a Python `if` statement do?
An `if` statement executes its indented block only when its condition evaluates to true.
What do the colon and indentation signify in an `if` block?
The colon begins the controlled block, and indentation identifies the statements belonging to it. Python conventionally uses four spaces per indentation level.
How does Python choose among `if`, `elif`, and `else` branches?
Python tests `if` and `elif` conditions from top to bottom, executes the first true branch, and skips the remaining branches. `else` runs when none is true.
Why should specific conditional tests come before broad tests?
Put the more specific or restrictive test first. Otherwise, a broader true condition may run before Python reaches the specific case.
What is the difference between `==` and `=` in Python?
`==` compares values, while `=` assigns a value to a variable.
When should Python use `is` instead of `==`?
Use `is` for object identity checks such as `value is None`; use `==` when comparing values.
What does `18 <= age < 65` mean?
A chained comparison such as `18 <= age < 65` is equivalent to `18 <= age and age < 65`; the middle expression is evaluated once.
What do Python’s `and`, `or`, and `not` operators do?
`and` is true only when both conditions are true, `or` is true when at least one is true, and `not` reverses a truth value.
How does short-circuit evaluation work?
Python evaluates `and` and `or` left to right and stops when the result is already known. A false left side stops `and`; a true left side stops `or`.
Which common Python values are false in conditionals?
`False`, `None`, numeric zero, and empty strings or containers are false in conditional contexts; most other values are true.
What does a collection mean when used directly as a condition?
Testing a collection directly checks whether it contains elements: an empty collection is false, while a nonempty collection is true.
What is a nested conditional?
Nesting places one conditional inside another. The inner condition is evaluated only when the outer condition succeeds, and its block must be indented farther.