Once you are feeling comfortable with the if, elif, and else statements, you can move on to nested conditional statements. We can use nested if statements for situations where we want to check for a secondary condition if the first condition executes as true. For this, we can have an if-else statement inside of another if-else statement. Let’s look at the syntax of a nested if statement:
A few possible outputs can result from running this code:
If, however, statement1 evaluates to true, but nested_statement evaluates to false, then the output will be:
And if statement1 evaluates to false, the nested if-else statement will not run, so the else statement will run alone, and the output will be:
We can also have multiple if statements nested throughout our code:
In the above code, there is a nested if statement inside each if statement in addition to the elif statement. This will allow for more options within each condition.
Let’s look at an example of nested if statements with our grade program. We can check for whether a grade is passing first (greater than or equal to 65%), then evaluate which letter grade the numerical grade should be equivalent to. If the grade is not passing, though, we do not need to run through the letter grades, and instead can have the program report that the grade is failing. Our modified code with the nested if statement will look like this:
If we run the code with the variable grade set to the integer value 92, the first condition is met, and the program will print out Passing grade of:. Next, it will check to see if the grade is greater than or equal to 90, and since this condition is also met, it will print out A.
If we run the code with the grade variable set to 60, then the first condition is not met, so the program will skip the nested if statements and move down to the else statement, with the program printing out Failing grade.
We can of course add even more options to this, and use a second layer of nested if statements. Perhaps we will want to evaluate for grades of A+, A and A- separately. We can do so by first checking if the grade is passing, then checkingto see if the grade is 90 or above, then checkingto see if the grade is over 96 for an A+ for instance:
In the code above, for a grade variable set to 96, the program will run the following:
Nested if statements can provide the opportunity to add several specific levels of conditions to your code.
Write a program that uses a one level nested IF.
Write a program that uses a two level nested IF.
Write a program that uses a three level nested IF.
Thanks [name] from [whichclass][location], Mr McG will get your message…"
[message]"…and will get back to you ASAP via [email]. Catch you soon.
Have a great day!!
K McGuinness - 2018
No personal data will be shared with any third party. The only data processed via this website is anonymous browsing data to best manage your user experience.