Python: Nested if Statements

  1. Introduction to Python
  2. Python: Choosing a Text Editor or IDE
  3. Python: Hello World
  4. Python: Variables, Strings and Numbers
  5. Python: Variable Naming
  6. Python: Math, Familiar
  7. Python: Math, Less Familiar
  8. Python: Mathematical Order of Operations
  9. Python: Introducing PEP 8
  10. Python: Text Concatenation
  11. Python: if Statements and Comparison Operators
  12. Python: else and elif statements
  13. Python: Testing Multiple Conditions
  14. Python: Testing Sets of Conditions
  15. Python: Nested if Statements
  16. Python: Lists
  17. Python: Adding To and Changing Lists
  18. Python: Lists: Take a Slice, Delete Elements, Popping Elements
  19. Python: Tuples
  20. Python: for Loops
  21. Python: Nested for Loops
  22. Python: Capturing and Formatting User Input
  23. Python: Dictionaries
  24. Python: Functions
  25. Python: While Loops
  26. Python: Creating and Using Classes
  27. Python: Data Files
  28. Python: Modules
  29. Python: CSV Files
  30. Python: JSON Files
  31. Python: Errors and Exception Handling
  32. Python: Using Pexpect
  33. Python : Using Pexpect : ftpTestOffload.sh
  34. Python : Using Pexpect: ftpTest.py
  35. Python: DCL Conversion to Python

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.")
else:
    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.

Exercises

See http://www.asmarterwaytolearn.com/python/13.html

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