if and else

Every program so far has run straight through, top to bottom. Conditionals let it choose.

An if statement takes a Boolean, everything you built in Module 6, and runs a block of code only when it's true. else handles every other case.

Branching

PYTHON

if age >= 18:
    print("Welcome in")
else:
    print("Not yet")

JAVASCRIPT

if (age >= 18) {
  console.log("Welcome in");
} else {
  console.log("Not yet");
}
Compare → Same logic, familiar scaffolding difference: Python uses a colon and indentation; JavaScript wraps the condition in parentheses and the body in braces. Note that JavaScript does NOT need parentheses around the whole if, just around the condition.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Only ONE branch ever executes. That's the whole point. Change age to 21 and run it, then add an elif (else if in JavaScript) so that 16 and 17 year olds see "You can pre-register".
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ The condition must produce a Boolean

Everything inside if(...) resolves to true or false before the branch is chosen. age >= 18 becomes True, then the if acts on it. This is why Module 6 came first: conditionals are just Booleans with consequences.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: elif: More Than Two Paths →
← Back