What are nested conditionals?
Conditional execution is a key instruction for any programming language. It checks conditions and runs the appropriate code.
if <boolean-express>:
statement
In case we have more than two possibilities, we can express conditionals using either chained conditionals or nested ones.
In this shot, we will learn about nested conditionals. We will use code snippets in Python, Java, JavaScript, and PHP.
What are nested conditionals?
Sometimes referred to as multiway branching, nested conditionals are the case where the else part of an if statement is itself an if statement.
A nested condition looks something like this:
if <boolean-expression-1>
<statement-1>
else
if <boolean-expression-2>
<statement-2>
else
<statement-3>
Here, we have a single statement representing a three-way branch. When the computer executes this, one of the three statements—statement-1, statement-2, or statement-3— will be executed.
Here’s how it works:
-
The computer starts by evaluating
boolean-expression-1. If it istrue, it executesstatement-1and then jumps to the end of the outerifstatement, skipping the other two statements. -
In case
<boolean-expression-1>isfalse, the computer skips<statement-1>and executes the second, nested if statement. To do this, it tests the value of<boolean-expression-2>and uses it to decide between<statement-2>and<statement-3>.
Let’s look at a simple implementation of this.
Code
The example below prints out one of three different messages, depending on the value of a variable named gender.
Python
# You can change the value of gender to see different msggender = "M"if gender == "M":print("You're a man.")else:if gender == "F":print("You're a woman.")else:print("I'm sorry, but I can't identify.")
Java
public class Gender {public static void main(String[] arg) {// You can change the value of gender to see different msgString gender = "F";if (gender == "M")System.out.println("You're a man.");else {if (gender == "F")System.out.println("You're a woman.");elseSystem.out.println("I'm sorry, but I can't identify.");}}}
JavaScript
// You can change the value of gender to see different msgconst gender = "N"if (gender == "M")console.log("You're a man.")elseif (gender == "F")console.log("You're a woman.")elseconsole.log("I'm sorry, but I can't identify.")
PHP
<?php// You can change the value of gender to see different msg$gender = "M";if ($gender == "M") {echo("You're a man.");}else {if ($gender == "F") {echo("You're a woman.");}else {echo("I'm sorry, but I can't identify.");}}
The flow of control for the example above can be seen in the following flowchart illustration.