close menu
Nested-Conditions-in-Programming Nested Conditions in Programming

Nested Conditions in Programming

13 February 2025

 Nested Conditions in Programming


Nested Conditions in Programming
Nested conditions refer to the placement of one conditional statement inside another. This allows for more complex decision-making structures where an additional condition is checked only if the first condition is met.

Syntax of Nested Conditions
if condition1:
   if condition2:
       # Code executed if both condition1 and condition2 are true
   else:
       # Code executed if condition1 is true but condition2 is false
else:
   # Code executed if condition1 is false

Example: Checking User Access
user_role = "admin"
user_status = "active"

if user_role == "admin":
   if user_status == "active":
       print("Access granted to the admin panel.")
   else:
       print("Admin access denied due to inactive status.")
else:
   print("Access denied. Admin privileges required.")

Explanation :
1. The first if checks if the user role is "admin".
2. If the user is an admin, the second if checks if their status is "active".
3. If both conditions are met, access is granted. otherwise, access is denied.

Nested conditions are useful in scenarios where decisions depend on multiple hierarchical conditions, ensuring a more structured and logical control flow.

Whatsapp logo