Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

A question, then a follow-up

A doctor asks first: do you have a fever? If you don't, that is the end of it. If you do, she asks a second question: for how many days? The second question only makes sense after the first answer.

Code does this by putting an if inside another if. The inner lines only get a turn when the outer condition is true. You can nest as deep as you like, but each level is more to keep in your head.

Nested if: the inner question only runs when the outer one is true.

Sorting triangles

Here's a good example. Three sticks can only form a triangle if any two of them are together longer than the third. That's the outer question. If it fails, the answer is "impossible".

If it passes, you ask the inner questions: are all three the same length (equilateral)? Are exactly two the same (isosceles)? Otherwise they are all different (scalene).

Check what is possible first, then ask what kind.
In code
if a + b > c and a + c > b and b + c > a:
    if a == b and b == c:
        kind = "equilateral"
    elif a == b or b == c or a == c:
        kind = "isosceles"
    else:
        kind = "scalene"
else:
    kind = "impossible"
Sticks of length 5, 5 and 8
a: 5
0
b: 5
1
c: 8
2
kind: ?
3
question
possible
yes

The outer question: can these sticks make a triangle at all? 5 plus 5 is 10, which is more than 8. The other two pairs pass too.

Move 1 of 4