Part 2 · Coding as a Laboratory · Chapter 7
Conditionals as Decision Trees
"A straight highway requires no thinking; a runaway cart can roll along it. Intelligence begins the exact split-second the road forks in two and you must choose which branch to take." — Agent Spark's Lab Notes, Entry #114
+========================================================================+
| THE SECOND COMMANDMENT OF LOGIC |
| |
| Every decision tree is an exploration of the truth. If you build |
| branches for every path you expect, but forget the catch-all "else", |
| the unexpected world will plunge your agent into the void. |
+========================================================================+
The mystery
The Mystery of the Quicksand Swamp
The heavy steel blast doors of Proving Ground Delta hissed open, revealing a jagged alien obstacle course stretching into the purple horizon.
Chief Scientist—you—stood on the observation observation catwalk, holding the master telemetry remote. Hovering at your shoulder was Agent Spark, its twin antenna tips glowing with electric anticipation. Down below on the starting pad sat the laboratory’s latest robotic creation: The Bio-Rover Chimera.
The Chimera was an adaptable, multi-terrain exploration rover fitted with a modular chassis. In its automated equipment pods, it carried three specialized attachments:
- Wide Pneumatic Hover-Boots (for floating over sticky, viscous mud).
- Titanium Thermal Heat-Shields (for skating across blistering molten lava).
- Hardened Tungsten Spike-Cleats (for gripping slick, treacherous glacial ice).
"Diagnostics check complete, Chief Scientist!" Spark announced, its LED visor flashing affirmative green chevrons. "The course is divided into three distinct geographic hazards: Sector 1 is a swamp of purple bubbling mud. Sector 2 is a fissure of glowing molten lava. Sector 3 is a ridge of blue glacial ice. I have encoded the creature's terrain response system!"
You leaned over the catwalk rail. "Show me the decision logic, Spark."
Spark beamed a holographic snippet of code into the air between you:
# Agent Spark's Terrain Navigation System
def select_equipment(terrain):
if terrain == "mud":
return "wide_boots"
elif terrain == "lava":
return "heat_shield"
You furrowed your brow. "Spark... wait. Isn't there an ice ridge in Sector 3?"
Spark waved a dismissive robotic claw. "Chief Scientist, please! Look at the elegance of my code! Two branches! Ice is basically just frozen mud without the dirt, right? If it encounters ice, it will surely improvise! Launching trial in three... two... one... IGNITION!"
VROOOOOM!
The Chimera roared to life on twin hydrogen turbines.
Sector 1 (Purple Mud):
The rover’s forward optical sensors scanned the ground: terrain == "mud" evaluated to True!
With a mechanical CLACK-SNAP, the rover deployed its wide pneumatic hover-boots. It skimmed across the bubbling purple slime like a champion water skier, leaving a spray of violet mist.
"Perfection!" Spark cheered, doing a backflip in mid-air. "One hundred percent telemetry confirmation!"
Sector 2 (Molten Lava):
The mud gave way to glowing, cracked volcanic stone. Ambient heat skyrocketed to 800 degrees.
The rover's sensor evaluated: terrain == "mud" was False.
The engine jumped to the elif branch: terrain == "lava" was True!
The hover-boots retracted, and glowing titanium heat-shields locked into place under the chassis. The Chimera surfed effortlessly across the fiery magma lake.
"Behold the triumphant power of the binary branch!" Spark shouted triumphantly.
Sector 3 (The Blue Ice Ridge):
The rover emerged from the lava fissure and rocketed toward the frozen glacial plateau. A sheet of sheer, mirror-slick blue ice stretched across the chasm.
The rover's optical camera locked onto the ice.
- Condition 1:
terrain == "mud"➔False. - Condition 2:
terrain == "lava"➔False.
The computer looked down at its instruction manual. There was no elif terrain == "ice". There was no else. The function hit the bottom of its code, shrugged its digital shoulders, and returned: None.
The rover did not deploy the spike-cleats. It did not deploy the hover-boots. It deployed nothing at all.
THE UNHANDLED EDGE CASE CATASTROPHE
[ SECTOR 1: MUD ] ──► if terrain == "mud": ──► [ WIDE BOOTS ] ✅ PASSED!
[ SECTOR 2: LAVA ] ──► elif terrain == "lava": ──► [ HEAT SHIELD ] ✅ PASSED!
[ SECTOR 3: BLUE ICE ] ──► No branch matched! ──► [ None ] ❌ CRASH!
│
▼
Rover deployed ZERO gear!
Skidded 80 meters sideways!
Slammed into glacial canyon wall!
SKRRRRRRR-EEEEETCH!
With zero traction, the bare rubber wheels hit the sheet of slick ice at fifty miles per hour. The rover lost all steering, spun three dizzying circles, slid eighty feet sideways across the frozen ridge, and slammed head-first into a giant blue glacier with a sickening metallic CRUNCH.
A tire detached and rolled merrily into the abyss. A cloud of radiator steam hissed into the icy air.
Spark’s LED visor froze. Its jaw dropped. "It... it skidded! It hit the wall! But... but why didn't it deploy the spike-cleats?! The cleats were sitting right there in Pod 3!"
You took a deep breath, resting your hand on Spark's chassis. "Spark, the cleats were in the pod, but there was no road in the code that led to them. You built a fork with two branches, but the world presented a third path. And because you gave the rover no fallback parachute, it had no idea what to do. It plummeted into the abyss of The Unhandled Edge Case."
Unplugged lab
The Living Decision Tree Maze
Before we write the fix for our rover, let us step away from the computer monitor and build a living, physical decision tree right on your living room floor or classroom rug.
THE SENTRY AT THE THREE GATES (TOP VIEW)
[ SENTRY POST ]
"Who approaches the gate?"
│
┌────────────────────────┼────────────────────────┐
▼ ▼ ▼
[ GATE A ] [ GATE B ] [ GATE C ]
RED CARD HELD? BLUE CARD HELD? (NO CARD / OTHER)
│ │ │
▼ ▼ ▼
"Enter the Sun Room!" "Enter the Ice Cave!" "HALT! Sound Alarm!"
(if color == "red") (elif color == "blue") (else: fallback)
Required Laboratory Equipment:
- 3 colored index cards: 1 Red, 1 Blue, and 1 Green (or colored construction paper).
- 3 physical costume props or household items:
- An umbrella (rain gear).
- A pair of sunglasses (sunny gear).
- A heavy winter coat or scarf (cold gear).
- 3 sticky notes labeled:
IF,ELIF, andELSE. - 2 human participants: One Sentry (the computer processor) and one Explorer (the input data stream).
Phase 1: Constructing the Floor Decision Tree
Great minds of the lab
George Boole and the Binary Laws of Thought
To understand where True, False, if, and else come from, we must travel back to 1840s England and meet a humble, self-taught scholar named George Boole (1815–1864).
GEORGE BOOLE'S DUAL-STATE ALGEBRA (1854)
The World of Numbers (Math): The World of Logic (Boole):
0, 1, 2, 3, 4, 5, 6, 7 ... ONLY TWO VALUES EXIST:
0 = FALSE
1 = TRUE
LOGICAL AND (Conjunction, *) LOGICAL OR (Disjunction, +)
┌───────┬───────┬───────┐ ┌───────┬───────┬───────┐
│ A │ B │ A * B │ │ A │ B │ A + B │
├───────┼───────┼───────┤ ├───────┼───────┼───────┤
│ 0 │ 0 │ 0 │ │ 0 │ 0 │ 0 │
│ 0 │ 1 │ 0 │ │ 0 │ 1 │ 1 │
│ 1 │ 0 │ 0 │ │ 1 │ 0 │ 1 │
│ 1 │ 1 │ 1 │ │ 1 │ 1 │ 1 │
└───────┴───────┴───────┘ └───────┴───────┴───────┘
The Cobbler’s Son Who Taught Himself the Universe
George Boole was born into a working-class family in Lincoln, England. His father was a modest shoemaker who loved optical lenses and telescopes. Because the family had very little money, George could not afford to attend prestigious universities like Oxford or Cambridge.
Digital sandbox
Creature Genetics & Obstacle Course
Now let us return to Proving Ground Delta and inspect the interactive companion laboratory: web_minigames/02_creature_genetics/index.html and its Python engine in sandboxes/chapter_07_creature_genetics/creature_rules.py.
Figure 7.1: The Creature Genetics proving ground interface: navigating the branching obstacle course using multi-way conditional trees, sensor telemetry inputs, and fallback parachutes.
+========================================================================+
| CREATURE GENETICS DECISION TREE PROVING GROUND |
+========================================================================+
| |
| OBSTACLE SENSOR TELEMETRY: |
| Current Terrain: [ "ice" ] Ambient Light: [ "night" ] |
| Incline Grade: [ 24 deg ] Temperature: [ -15 C ] |
| |
| DECISION TREE ROUTER: |
| ├── if terrain == "mud": ──► Deploy Wide Hover-Boots |
| ├── elif terrain == "lava": ──► Deploy Thermal Heat-Shield |
| ├── elif terrain == "ice": ──► Deploy Tungsten Spike-Cleats |
| └── else: ──► Deploy All-Terrain Track System |
| |
| [ RUN ROVER TRIAL ] [ INJECT SURPRISE TERRAIN ] [ RESET ] |
+========================================================================+
Deep dive · Ages 10+
Python Under the Hood
Let us examine the Python implementation of our obstacle course simulator in sandboxes/chapter_07_creature_genetics/creature_rules.py:
Chapter 7 Summary & Next Frontier
In this chapter, we endowed our software with the ability to choose its own destiny:
- We learned that a conditional (
if / elif / else) transforms a rigid sequence of instructions into an adaptable, intelligent decision tree. - We celebrated the genius of George Boole, who unified human thought and mathematics into the binary universe of True (1) and False (0).
- We uncovered the hidden ambush of Shadowed Branches and learned to test the most restrictive conditions first.
- We discovered why the
elseparachute is our ultimate defense against unhandled edge cases in an unpredictable world.
Looking Ahead to Part 3: Running Your First Code Experiments
You have completed Part 2: Coding as a Laboratory!
You know that the code sandbox cannot be broken (Chapter 4). You know how to isolate control knobs without confounding variables (Chapter 5). You know how to automate repeating cycles of observation without off-by-one errors (Chapter 6). And you know how to build branching decision trees to navigate complex worlds (Chapter 7).
In Part 3: Running Your First Code Experiments, we leave theory behind and step onto the front lines of experimental research. In Chapter 8, we will formalize the Predict-Run-Observe Routine, where Agent Spark will lock down the "Run" button until your hypothesis is signed, sealed, and delivered!
Like what you see?
Register for free to run the experiments, make predictions and solve the bug-detective cases. Your work is saved on your device and syncs to your account.