Skip to main content
Practice

Conditions within Conditions, Nested Conditionals

In programming, sometimes complex logical flows are required depending on different situations.

For example, consider writing a program to provide a discount based on whether someone is 18 years or older and whether that person is a student.

It may be difficult to implement the desired logical flow with just one conditional statement.

In such cases, nested conditional statements can be used to handle the problem.


What is Nesting?

Nesting means "something inside another", and a nested conditional means placing one conditional statement inside another.

Leveraging nested conditionals allows you to add additional checks only when a specific condition is satisfied, thereby creating a more complex and detailed logical flow.


How to Use Nested Conditionals?

Let's write a program to cover the earlier mentioned conditions where:

  1. Someone is 18 years or older, and

  2. That person is a student.

The program will provide discounts based on these conditions.

Example of Nested Conditionals
age = 20
is_student = True

if age >= 18:
if is_student:
print("Eligible for student discount")
else:
print("Adult rate applies")

In this code, the first if conditional checks if the age is 18 or older.

If this condition is true, the nested if conditional inside it is executed.

Here it checks if the is_student variable is true; if it is, it prints "Eligible for student discount", otherwise, it prints "Adult rate applies".

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.