Conditionals
- if
- if-else
max_value
- if-elsif-else
- too hot / too cold / just right
- if-elsif-elsif-elsif-else
- Letter grades
- Indentation matters
- Spaces different than tabs
=vs==- Operator chaining
a < b C- somewhat unique to Python
and/or/not!=as shortcut fornot x == y
- implicit vs explicit ranges
- i.e., choosing order of if statements carefully
- Look at letter grades again.
- chain of if vs. else-if
- nested if
- Compute bonus for different structures
- Structure A: 10% for sales over 10,000
- Structure B: $100 if sales is a multiple of 5.
- Compute bonus for different structures
- integers and floats can be compared. (One is coerced)
- strings can be compared using
==,<,<=, etc. - can’t directly compare strings and integers
- Avoid comparing
floatusing==- Why?
isvs ==- watch for
if x = 9:(instead of==)-
Example
def print_discount(has_discount: bool): if (has_discount = True): print('You have a discount!') else print(f"No discount. (Your status {has_discount})") print_discount(False) - Actually, this is a syntax error. Need to use
:=. - The requirement of the
:is to avoid this common mistake.
-
- Order of operations
- precedence:
not,and,or not x or yis evaluated as(not x) or y.x == 5 or y == 10 and z != 10is evaluated as(x == 5) or ((y == 10) and (z != 10))becauseandhas precedence overor.- When in doubt, just use parentheses.
- precedence:
-
conditional/ ternary operator
x = 18 parity = 'even' if x %2 == 0 else 'odd' - Expression trees