Your route · 0 of 17 done
MODULE 00 · PROGRAMMING BASICSStep 4 of 8About 30 min

Making decisions

By the end of this step your program can do different things depending on the data, and count things that match a rule.

if: only when it's true

An if runs some lines only when a condition is true:

PythonJavaScript
Ifif price > 100:if (price > 100) { … }
Otherwise, ifelif price > 20:else if (price > 20) { … }
Otherwiseelse:else { … }

The program checks the conditions top to bottom and runs the first one that's true. Only one branch runs.

Conditions compare values:

MeansWrite
greater than, less than> <
at least, at most>= <=
is equal to== (Python) or === (JavaScript)
is not equal to!= (Python) or !== (JavaScript)
both must be trueand (Python) or && (JavaScript)
either can be trueor (Python) or || (JavaScript)

Careful: one = stores a value; two (or three) compare. Mixing them up is a classic mistake.

Try it

Python: decisions · runs in your browser

Output

Press Run (or Ctrl+Enter) to see the output here.

JavaScript: decisions · runs in your browser

Output

Press Run (or Ctrl+Enter) to see the output here.

Two patterns to take away:

  1. Sorting into groups. if / elif / else puts each product in exactly one bucket.
  2. Counting. Start a counter at 0; inside the loop, add 1 only when the condition is true. It's the running total from the last step, with an if in front.

The description checker you'll build uses both: is this description too short? If so, count it.

Your turn

At the bottom of either box, count how many products cost between $20 and $100. You should get 2 (the Headlamp and the Sleeping Pad).

    Next: Functions