Hone

Lessons · Python · if / else

Choosing between two paths

if runs its block when the condition is true, and else runs when it is not. Exactly one of them happens.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Software is decisions. Is this user logged in, is the cart empty, did the payment clear. Every one of those is this shape, and everything else is built on top of it.

How to think about it

Ask: what is the question, and what should happen for each answer? Write the question as something that is either true or false, then handle both.

Worked example

age = 15
The value we are deciding about.
if age >= 18:
The question. It is either true or false, never both.
    print("adult")
Indented, so it belongs to the if. This does not run here.
else:
Everything the if did not catch.
    print("minor")
This is what actually prints, because 15 is not 18 or more.

Your turn

Print "empty" when a list has no items.

items = []
if len(items) == :
    print("empty")
else:
    print("has things")

The trap

Using = instead of == in the condition. One assigns, the other compares, and Python will stop you, which is kinder than languages that do not.

Practise if / else on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.