What are chained conditionals?
In a previous shot, we learned how to express conditionals with nested conditionals. Today, we will learn how to simplify nested conditionals with chained conditionals.
Let’s get started.
Chained conditionals in one word
Chained conditionals are an alternative way to write nested conditionals.
The format for these conditionals looks like this:
if <boolean-expression-1>
<statement-1>
else if <boolean-expression-2>
<statement-2>
else
<statement-3>
The else clause is optional and always comes at the end of the conditional. There is no limit on
the number of else if statements.
Note: Only one branch will be executed.
Now is the time to implement. We’ll be using the same example as in the shot on nested conditionals.
Code implementation
# You can change the value of gender to see different msggender = "M"if gender == "M":print("You're a man.")elif gender == "F":print("You're a woman.")else:print("I'm sorry, but I can't identify.")
Note: In Python,
elifis an abbreviation forelse if.
Flow of control
The flow of control for the chained conditionals is as follows:
Ordering valid conditionals
Below are some examples of how valid conditional statements are ordered.
// code block
if
// code block
// code block
if(...) {...}
else {...}
// code block
// code block
if(...) {...}
else if(...) {...}
else {...}
// code block
// code block
if(...) {...}
else if(...) {...}
else if(...) {...}
// code block
That’s all for today. Happy coding!