First If

Home / Guides

How to Write an If Statement: A Step-by-Step Method for Any Language

Writing an if statement is a translation job, not a creative one. Four steps, one worked example, and the checks that stop a boundary bug before it ships.

Writing an if statement is not a creative act, which is good news. It is a translation job: there is a rule in your head, and your task is to say it in a form the computer can check. Get the rule clear first and the code is nearly mechanical. Here is the method, step by step, with the same example carried through.

The four steps

  1. Say the rule in plain English. One sentence, no code, no variables.
  2. Name the thing you are checking. Whatever appears in the sentence becomes a variable.
  3. Pick the comparison operator. Equal, different, bigger, smaller, bigger-or-equal, smaller-or-equal.
  4. Write the block and test it twice. Once true, once false.

Beginners usually skip steps 1 and 2 and start typing at step 3. That is where inverted conditions and half-remembered variable names come from.

Step 1: the rule, in English

Suppose you are building a checkout and the shop offers free shipping. The rule in your head is:

Free shipping when the order is over 50.

Notice what that sentence does and does not say. It does not say what happens below 50 — you have to decide that separately (charge shipping, presumably). It also uses the word "over", which is a decision in itself: is an order of exactly 50 free? English is vague here and code is not, so step 1 always ends with a question you answer out loud. In this case: exactly 50 counts, so "50 or more".

Step 2: name the thing you are checking

The sentence contains one quantity: the order total. In code, a quantity is a variable with a name you choose. Call it order_total — descriptive, no spaces, obviously about money:

python
order_total = 62.50

Two naming habits are worth keeping from day one. Use the same word in the code as in the rule, so you can read the code aloud and hear whether it matches. And keep a unit or domain hint where it helps: order_total is clearer than x, and age_years is clearer than age when you have several ages floating around.

Step 3: pick the operator

Turning the English word into a symbol is the only genuinely error-prone part. Match the phrase, not the vibe:

EnglishOperatorWhy people slip
is / are / equals==They type =, which assigns instead of comparing
is not / different from!=The ! goes first, not second
more than / above / over>This excludes the number itself
at least / over or equal to>=Forgetting the = off by one boundary
less than / below / under<Mixed up with > when the variable is on the right
at most / up to and including<=Same boundary problem

Because the rule said "50 or more", the condition is order_total >= 50. Write it on its own line first and read it back to yourself as a sentence. If the sentence you read is not the rule from step 1, stop and fix it now — before there is any code around it to distract you.

Step 4: write the block, then test both paths

python
order_total = 62.50

if order_total >= 50:
    print("Free shipping applied.")
else:
    print("Shipping: $5.00")

Now do the part almost everyone skips. Run it once with 62.50 and once with 31.00. Then run it with 50 — the boundary — because that is the value your rule was vague about and the value most likely to be wrong. Three runs, ten seconds, and the condition is proven rather than assumed.

The same program in JavaScript:

javascript
const orderTotal = 62.5;

if (orderTotal >= 50) {
  console.log("Free shipping applied.");
} else {
  console.log("Shipping: $5.00");
}

Parentheses around the condition, braces around the block, semicolons at the end of statements. The condition itself is unchanged — which is exactly why learning the method is worth more than memorising one language's punctuation.

The syntax map, if you need to switch languages

LanguageYou write
Pythonif total >= 50: then an indented block
JavaScriptif (total >= 50) { ... }
Java / C#if (total >= 50) { ... }
PHPif ($total >= 50) { ... } — variables carry a $
Goif total >= 50 { ... } — no parentheses, braces mandatory
Rubyif total >= 50 then the block, closed with end
SQLCASE WHEN total >= 50 THEN 'free' ELSE 'paid' END

Test with a truth table, not with hope

A truth table is a plain list of the inputs that matter and the output you expect. You do not need a testing framework to use one — write it as a comment above your code:

text
# 49.99 -> paid
# 50.00 -> free   (boundary: this is the one that breaks)
# 50.01 -> free

Three lines, written before you run anything, and now "it seems to work" has been replaced by a check you can repeat. When the program grows and someone changes the rule to 75, that comment is the specification.

Make long conditions readable

A condition with three parts is a sign that the rule has a name. Give it one:

python
is_new_customer = orders_count == 0
qualifies_for_promo = order_total >= 50 and is_new_customer

if qualifies_for_promo:
    apply_discount()

The if statement is now almost trivial, and the interesting thinking lives in a line with a name. Two benefits follow immediately: you can print qualifies_for_promo when the discount fails to appear, and you can reason about each half separately.

Edge cases that decide whether it survives real users

  • User input is text. Whatever someone types arrives as a string. "62.5" >= 50 is an error in Python and quietly wrong in JavaScript. Convert first, and handle the case where conversion fails.
  • Empty values. None and null are not zero. Compare against them with is None in Python or === null in JavaScript, and check before doing arithmetic.
  • Money in floating point. 0.1 + 0.2 is not exactly 0.3. For prices, work in whole cents (integers) so a boundary comparison means what you think it means.
  • Case and whitespace in strings. Trim and normalise before comparing, or accept that "Yes " will take the wrong branch.

A checklist to run before you move on

  • The condition, read aloud, is the same sentence as the rule.
  • Two equals signs, not one.
  • The boundary value was tested by hand.
  • Both paths were actually run.
  • The block is indented consistently (Python) or braced (everything else).
  • If there is an else-if chain, its order is narrow to wide, and it ends with a default.
  • Any condition longer than two parts has a name.

Practice

  1. Write the rule for a cinema: a ticket is 12, but under 12s pay 6 and over 65s pay 8. Say the rule in English first, then name the variable, then pick the operators.
  2. Write a form validation with three outcomes: missing email, email without an @, and email that looks fine.
  3. Write a shipping rule with two conditions joined by and: free shipping over 50 and a member. Then decide what happens for a member spending 20.

The method, one last time

Say the rule. Name the quantity. Pick the operator. Write the block. Test true, test false, test the boundary. Five minutes of that order saves an hour of debugging out of order.

Common questions

How do I write an if statement in Python?

Write if, then the condition, then a colon, then indent the block by four spaces. Python uses indentation instead of curly braces.

Should I use = or == in a condition?

Two equals signs compare values and give true or false. A single equals sign assigns a value. In a condition you almost always want two.

How many conditions should one if statement have?

If a condition needs more than two and/or parts, give it a name in a variable first. A named condition is easier to read and easier to test.

How do I test an if statement properly?

Run it three times: once where the condition is obviously true, once where it is obviously false, and once on the boundary value, such as exactly 18 for an age check.

Ask a question

Not sure why your if never runs? Send it over.

Your message comes straight to the person who writes the guides. We answer real questions.

Powered by LunaNineAI.com

This is a demo version of this site.

Contact us to claim this site.