All lessons
🔀Programming 6 min read

If Statements

How your project makes decisions instead of just repeating itself.

In 10 seconds

  • if asks a yes/no question, else is the other path.
  • = sets a value, == compares two values.
  • Combine tests with && (and) and || (or).

Up to now your programs have been like a recipe: do this, then this, then this. An if statement changes everything, because it lets the program look at the situation and choose. It is the difference between a light that blinks and a light that comes on when it gets dark.

The basic shape

You write the word if, a question in round brackets, and the instructions to run in curly braces. If the question is true, the braces run. If not, they are skipped entirely and the program carries on below.

You can add else for what should happen otherwise, and else if to test another question before giving up. A night light might say: if it is very dark, full brightness; else if it is a bit dim, half brightness; else, off.

Asking the question properly

The comparison symbols are mostly what you would expect, with one famous trap:

  • == is equal to (two equals signs!)
  • != is not equal to
  • > and < greater than, less than
  • >= and <= greater or equal, less or equal

The trap is that a single = means "put this value in the box", not "are these the same?". Writing if (x = 5) quietly sets x to 5 and then always runs the block. It is one of the most annoying bugs in all of programming, and every single person reading this will make it eventually.

Combining questions

Real decisions often need more than one condition. Use && for "and" — both must be true — and || for "or" — at least one must be true. An exclamation mark ! flips a condition to its opposite.

So an alarm that only sounds at night when motion is detected asks: if it is dark and the sensor sees movement. A warning that triggers at extremes asks: if it is too hot or too cold.

Thinking in states

A very common beginner problem: your door servo keeps re-opening because the motion sensor is still HIGH. The fix is to ask a smarter question. Instead of "is there motion?", ask "is there motion and is the door currently closed?". You keep a boolean variable that remembers the door's state, and the if statement checks both.

This pattern — remember what happened, then decide based on the change rather than the raw reading — is the single biggest step from beginner code to code that behaves well.

A word about tidiness

If statements can nest inside each other, and after three or four levels the code becomes very hard to follow. When that happens, it is usually a sign to pull the inner part out into a function with a descriptive name. Your future self will thank you.

Quick quiz: If Statements

3 questions to check it stuck.

Take the quiz

Next lesson

🔁 Loops

Keep learning

Ready to try it for real?

Reading is good. Wiring is better. Pick a project and put this to work.

Explore projects