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:
| Python | JavaScript | |
|---|---|---|
| If | if price > 100: | if (price > 100) { … } |
| Otherwise, if | elif price > 20: | else if (price > 20) { … } |
| Otherwise | else: | else { … } |
The program checks the conditions top to bottom and runs the first one that's true. Only one branch runs.
Conditions compare values:
| Means | Write |
|---|---|
| greater than, less than | > < |
| at least, at most | >= <= |
| is equal to | == (Python) or === (JavaScript) |
| is not equal to | != (Python) or !== (JavaScript) |
| both must be true | and (Python) or && (JavaScript) |
| either can be true | or (Python) or || (JavaScript) |
Careful: one = stores a value; two (or three) compare. Mixing them up is a classic mistake.
Try it
Output
Press Run (or Ctrl+Enter) to see the output here.
Output
Press Run (or Ctrl+Enter) to see the output here.
Two patterns to take away:
- Sorting into groups.
if/elif/elseputs each product in exactly one bucket. - 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 anifin 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).