Python: Nested if Statements

Go to Chapter 13 of A Smarter Way.

Now we’re into multiple nested conditions: if it’s 6:00 AM, and if you’re near a coffee shop, and if you have $5, it would be nice to get a latte.

if time <= 6:00AM:
    if coffee_shop_miles_distance < 1:
        if dollars_on_hand >= 5:
            print("Get a cup of coffee!")
        elif dollars_on_hand < 5:
            print("No coffee for you.")
    print("It's too late for coffee.")

All that’s necessary is to indent consistently. Each sub-block should get its own extra indentation. You can have elif and else at any level, with the usual functionality.



  1. Continue editing
  2. Create an example code block that uses two layers of if statements, and also uses else and elif at least once.