Nested Conditionals
Nested Selection
Part of: Algorithms, Iteration & Simulation
Real decisions often depend on a second question only after a first one is answered. Placing one conditional inside another creates a nested conditional , letting you express layered rules. A conditional inside a conditional Imagine a movie ticket. Children under 13 always pay $5. For everyone else, the price depends on whether they are a member: The outer if splits people into child vs. everyone else . Only inside the else branch, the adult path, does the program ask the second question about membership. A child never reaches the membership test at all. This is the essence of nested selection : the inner decision is reached only when the outer condition has already been settled. Reading the indentation Indentation shows the nesting depth. The inner if/else is indented one level further because it lives inside the outer else. Trace it carefully: - age = 10 - outer condition True - price = 5, inner block skipped. - age = 30, member = "yes" - outer False - inner True - price = 8. - age = 30, member = "no" - outer False - inner False - price = 12. Nesting vs. elif Many nested chains can be flattened with elif, which is often clearer. But true nesting shines when the inner question is
Challenge: Ticket Price