Conditional Operators Flashcards
if, elif, else
Conditional Operators
Used to take decisions in our code based on a condition.
If signal is green, we go
If signal is yellow, we slow down
If signal is red, we stop
Here, signal is the condition that determines the decision
Family of conditional operators
To take a single decision, we might have different factors (like green, yellow and red). So we group them into a family of conditional operators. For example,
If signal is green, we go (one specific condition)
Else if the signal is yellow, we slow down (not the first condition, but a second specific condition)
Else if the single is red, we stop (not the first two conditions but this is also a specific condition that the light HAS TO BE red - so, else if)
Else raise a complaint (this means, none of the three specific conditions are met, so anything other than those three conditions, use this - else)
if condition
if (myAge > sisterAge):
print(‘I am the elder sister’)
is same as
condition = myAge > sisterAge
if (condition == True):
print(‘I am the elder sister’)
Else if condition
Else if in python is written as elif
elif (myAge < sisterAge):
print(‘I am the younger sister’)
Can you think what would be the else case in this example?
If myAge is greater, we print I’m the elder sister
else if myAge is smaller, we print I’m the younger sister
What do you think would be the else part?
else:
print(‘We are twins!’)