Practice Session
- Sunday at 6PM
Reading Questions
Quiz
Nested Conditionals
- Just like with loops, we can put any code we want inside a conditional statment block, including more conditionals
Putting a condition inside of another is equivalent to using the
and
operatorif x > 0: if x < 10: print('x is greater than 0 and less than 10)
Chained Conditionals
- An
else
block is executed if the previous if statement is not true - It can not have any condition
- An
elif
, a combination of else and if, is a chimera of anif
and anelse
. It has a condition like an
if
, but the condition is only checked if the previous condition was not trueif x < 0: print('x is negative') elif x < 10: print('x is not negative but is less than 10') else: print('x is greater than or equal to 10')
- Each condition in a chain of elifs is only tested if all of the previous were not true
- taking advantage of this, it is sometimes possible to reduce the number of logical operators used
For example, the following more verbose code is functionally equivalent to the above code
if x < 0: print('x is negative') if x > = 0 and x < 10: print('x is not negative but is less than 10') if x >= 10: print('x is greater than or equal to 10')