Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
java
javascript
php
communitycreator

What are chained conditionals?

Abel Lifaefi Mbula

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 msg
gender = "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.")
Chained if statements in Python

Note: In Python, elif is an abbreviation for else if.

Flow of control

The flow of control for the chained conditionals is as follows:

Flow of control

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!

RELATED TAGS

python
java
javascript
php
communitycreator
RELATED COURSES

View all Courses

Keep Exploring