02

Phase 1 - Level 2: Nested If & Multiple Conditions

Chapter 2 • Beginner

60 min

Phase 1 - Level 2: Nested If & Multiple Conditions

Introduction

As problems become more complex, you need to check multiple conditions or nest conditions inside each other. This level teaches you how to combine conditions effectively.

Logical Operators

Python provides three logical operators to combine conditions:

  • and: Both conditions must be True
  • or: At least one condition must be True
  • not: Reverses the boolean value

Nested If Statements

You can place if statements inside other if statements:

python.js
if condition1:
    if condition2:
        # Both conditions are True
        statement1
    else:
        # condition1 is True, but condition2 is False
        statement2
else:
    # condition1 is False
    statement3

Multiple Conditions with AND

python.js
if condition1 and condition2:
    # Both must be True
    statement

Multiple Conditions with OR

python.js
if condition1 or condition2:
    # At least one must be True
    statement

Common Patterns

  • Triangle Validation: Check if three sides form a valid triangle, then determine type
  • Grade Calculation: Use multiple conditions to assign grades
  • Age-based Rules: Combine age and other conditions for eligibility
  • Time-based Greetings: Check hour ranges for different greetings

Best Practices

  1. Readability: Use parentheses to clarify complex conditions
  2. Order Matters: Check simpler conditions first (short-circuit evaluation)
  3. Avoid Deep Nesting: Try to keep nesting levels reasonable (2-3 levels max)
  4. Use elif: Prefer elif over nested if when checking multiple exclusive conditions

Hands-on Examples

Check Triangle Type

# Take three sides as input
a = float(input("Enter side 1: "))
b = float(input("Enter side 2: "))
c = float(input("Enter side 3: "))

# Check if valid triangle
if a + b > c and b + c > a and c + a > b:
    # Valid triangle - determine type
    if a == b == c:
        print("Equilateral")
    elif a == b or b == c or c == a:
        print("Isosceles")
    else:
        print("Scalene")
else:
    print("Invalid triangle")

First check if sides form a valid triangle (sum of any two sides > third side). Then check if all sides equal (equilateral), two sides equal (isosceles), or all different (scalene).