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.

  1. Ask Oil left? and store the answer as an int in oil (this line is done for you).
  2. If oil is greater than 0, print The lantern is lit!
  3. Otherwise (else), print The lantern is dark.