
Code
If This, Else That
Programs get interesting when they choose. First, we need
questions with yes/no answers. Comparison operators give a
True or False:
| Operator | Asks | Example | Result |
|---|---|---|---|
== |
equal? | 3 == 3 |
True |
!= |
not equal? | 3 != 3 |
False |
< > |
less / greater? | 2 < 5 |
True |
<= >= |
or equal? | 5 >= 5 |
True |
Careful: = stores a value, but == compares. Mixing them
up is the classic slip!
Now if runs a block only when the condition is True.
else runs when it's False:
oil = 3
if oil > 0:
print("The lantern glows")
else:
print("The lantern is dark")
print("Goodnight!")
Note the colon : and the 4-space indent. The
indented lines belong to that branch. Goodnight! is not
indented, so it prints every time.
Assignment
The Input box holds one answer: 5.
- Ask
Oil left?and store the answer as an int inoil(this line is done for you). - If
oilis greater than0, printThe lantern is lit! - Otherwise (
else), printThe lantern is dark.
The Input box holds one answer: 5.
- Ask
Oil left?and store the answer as an int inoil(this line is done for you). - If
oilis greater than0, printThe lantern is lit! - Otherwise (
else), printThe lantern is dark.
main.py Python sleeping
Press Run to try your code, then Check to test it.