Consider the function category that takes an integer and returns a single string
indicating whether it's even or odd and whether it's negative or not:
def category(n):
if n%2 == 0:
evenOrOdd = 'even'
else:
evenOrOdd = 'odd'
if n < 0:
negOrNot = 'neg'
else:
negOrNot = 'nonneg'
return f"{evenOrOdd} {negOrNot}"
For example:
>>> category{17}
'odd nonneg'
>>> category{-42}
'even neg'
The body of category uses two conditional statements, each of which uses the result
of a test expression to to choose beween
executing a then branch statement sequence or an else branch statement sequence.
if testExp:
thenBranchStm_1
...
thenBranchStm_m
else:
elseBranchStm_1
...
elseBranchStm_n
But Python (and most other programming languages) also has a
conditional **expression** construct that uses the result of a
_test expression_ to to choose beween the result of evaluating
a _then branch expression_ or an _else branch expression_:
```python
thenBranchExp if testExp then elseBranchExp
It turns out that expressions are typically more flexible and powerful than statements, so you are strongly encoraged to use conditional expressions rather than conditional statements in situations where they are sensible.
Here is one way to use conditional expressions to implement
a version of the category function above:
Table of Contents
- Lab 3 Home
- Defining Predicates without Conditionals
- Conditional Expressions
- Conditional and While Loop Exercises