2. Making Choices
Programs get interesting when they can make decisions. “If the creature is hungry, look for food.” This page shows how.
True and False
A decision is always about something being True or False. In Python these are special words (with a capital first letter):
Comparing things
To make a decision, you compare values. Each comparison gives back True or False.
| Symbol | Means | Example | Result |
|---|---|---|---|
== | is equal to | 5 == 5 | True |
!= | is not equal to | 5 != 3 | True |
> | is greater than | 10 > 3 | True |
< | is less than | 10 < 3 | False |
>= | is greater than or equal to | 5 >= 5 | True |
<= | is less than or equal to | 4 <= 5 | True |
⚠️ Watch out: one = puts a value in a box. Two == asks “are these the same?”. They are different!
if — do something only when it’s true
An if runs the code inside it only if the test is True.
Output:
Two very important rules
- The line with
ifends in a colon: - The code that belongs to the
ifis indented (pushed in) by 4 spaces.
That indent is how Python knows which lines belong to the if. If you forget it, you’ll get an error.
Output:
(The first two lines were skipped because 50 is not less than 30.)
if / else — do one thing OR another
else gives you a “otherwise” path. One of the two blocks will always run.
Output:
if / elif / else — choosing between many options
elif means “else, if…”. Use it to check several things in order. Python checks them from top to bottom and runs the first one that is True, then stops.
Output:
You can have as many elif lines as you want. The else at the end is optional — it catches “none of the above”.
Combining tests: and, or, not
Sometimes one test isn’t enough.
and — both must be true:
or — at least one must be true:
not — flips True to False and back:
✅ Quick recap
- Comparisons like
==,>,<give backTrueorFalse. ifruns code only when the test isTrue.- Add
elsefor an “otherwise” path. - Add
elifto check more options in order. - Remember the colon
:and the 4-space indent. - Join tests with
and,or, andnot.