An if statement is the smallest piece of code that makes a decision. It asks a yes-or-no question, and the answer decides whether the next few lines run at all. If you have written a program that printed the same thing no matter what you typed in, an if statement is what was missing.
Short version: a condition is a question with two possible answers, true or false. An if statement runs its block when the answer is true, and skips the block when the answer is false.
The same idea in plain English, then in code
Here is a rule you already follow without thinking about it:
If the door is locked, ask for the key.
Turned into code, that rule keeps its shape. Only the spelling changes:
if door_is_locked:
ask_for_key()Read that out loud and it still sounds like a sentence. if starts the question, door_is_locked is the question, the colon marks the end of the question, and the indented line is what happens when the answer is yes.
Why programs need decisions at all
Without conditions, a program is a list. It does the same six things in the same order every time, for every user, forever. Add a condition and the list becomes a path through the possibilities. Password checks, discount rules, "you are out of stock", "your session expired", "show the mobile layout" — every one of those is an if statement wearing a different costume.
This is why beginners hit a wall at exactly this point. Variables, printing and arithmetic all feel like maths homework. The first if statement is where the code starts to feel like it is thinking.
The three parts of every if statement, in every language
Languages disagree about punctuation and agree completely about structure. Every if statement has these three parts:
- The keyword.
ifin Python, JavaScript, Java, C#, PHP, Go, Ruby and Swift. You already know this word. - The condition. Something that is either true or false. It is not a question mark and it is not a sentence — it is a comparison, or a value that can be read as true or false.
- The block. The code that belongs to the if. In Python it is marked by indentation. In most other languages it is wrapped in curly braces.
That is the whole anatomy. Anything else you see in a real if statement is an optional extra.
A complete first example
Say you are writing a sign-up form and the rules say adults only. You have the person's age in a variable called age. The condition is the rule, written as a comparison:
age = 15
if age >= 18:
print("Welcome! Your account is ready.")
print("This line always runs.")Run that and you see only the second line. Change age to 42 and both lines appear. Nothing else in the program changed — only whether a condition came out true.
The same program in JavaScript, so you can see what carries over and what does not:
const age = 15;
if (age >= 18) {
console.log("Welcome! Your account is ready.");
}
console.log("This line always runs.");Two differences: JavaScript puts the condition in parentheses, and it wraps the block in braces instead of indenting it. The condition — age >= 18 — is identical, and it would be identical in Java, PHP, Go, Ruby and Swift too. Conditions travel between languages. Punctuation does not.
Where conditions come from
A condition is built from a comparison operator. There are only six, and you have used all of them since primary school:
| Operator | Ask this | Example that is true |
|---|---|---|
== | Are these equal? | status == "active" |
!= | Are these different? | status != "banned" |
> | Is the left bigger? | balance > price |
< | Is the left smaller? | stock < 3 |
>= | Is the left bigger or equal? | age >= 18 |
<= | Is the left smaller or equal? | items <= 10 |
Join two conditions with and (Python, Ruby) or && (JavaScript, Java, PHP) when both must be true, and with or or || when either one is enough. Prefix a condition with not or ! to flip it, and use that sparingly — not is_closed is harder to read than is_open.
The mistake everyone makes once: a single = is assignment, not comparison. if price = 10 does not ask whether the price is ten, it tries to set it. In Python that is an outright error. In JavaScript it silently succeeds and your condition becomes whatever value was assigned — a bug that can waste an afternoon. Comparison needs two equals signs.
Truthy and falsy: conditions that are not comparisons
Some values count as true or false all by themselves. In Python, 0, 0.0, "", [], {} and None are falsy; nearly everything else is truthy. JavaScript adds null, undefined, NaN and the string "0"... except that "0" is actually truthy in JavaScript, which is exactly the kind of detail that argues for being explicit.
Which is the real advice: be explicit at the start. Write if len(cart) > 0 rather than if cart, and if name != "" rather than if name. You will spend less time wondering why an empty list took the wrong branch. Once the explicit form is automatic, the short form becomes a readability tool instead of a trap.
What an if statement is not
- It is not a loop. An if statement runs its block once, or not at all. It never repeats. Repeating is a
fororwhileloop's job. - It is not a function. It does not get called and it does not return anything. It is a decision in the middle of whatever was already running.
- It is not a filter. It does not remove data. It chooses which lines of code run — the data stays exactly as it was.
Five mistakes that catch almost every beginner
- Forgetting the block. An if with nothing under it is either an error or dead weight. If you are not ready to write the body, write
pass(Python) or a comment, and come back. - Indentation that looks right but is not. Python is strict: four spaces, the same four spaces on every line of the block. Mixed tabs and spaces produce confusing errors or, worse, code that joins the wrong block.
- Comparing different types.
"18" >= 18is an error in Python and quietly false in JavaScript. Convert first:int(age_input),Number(ageInput). - Checking the opposite of what you meant.
if age < 18: print("welcome")reads fine and does the reverse. Say the rule out loud, then check the operator against it. - Testing only one case. One run that happens to take the true branch proves very little. Run it again with a value that should be false.
When you reach for an if statement
Use one when a rule in your head has the word "if" in it: if the email is missing, show an error; if the total is over 50, apply free shipping; if the user is logged in, greet them by name. Those are requirements, and an if statement is the direct translation of a requirement into code.
Reach for one when you are validating input, before you use it. Reach for one when a calculation has a special case. Do not reach for one to repeat something — that is a loop — and do not pile up eight conditions in a row when a single named condition would explain the rule better.
Practice, right now
Type these out by hand. Do not copy and paste; the typing is where the syntax sticks.
- Ask for a temperature. If it is above 25, print "Wear shorts." Run it twice: once with 30, once with 12.
- Store a password in a variable. Ask the user to type it. If they match, print "Access granted." Then deliberately get it wrong and confirm nothing prints.
- Store a shopping total. If it is over 50, print "Free shipping." If it is over 100, print "Free shipping and a gift." Note what happens when the total is 120 — that surprise is why the if/else guide exists.
The one thing to remember
An if statement is a rule from your head, written in a form the computer can check. Get the rule clear in English first, and the code is nearly a transcription. If you cannot say the rule in one sentence, the condition is not the problem — the requirement is.
Common questions
What is an if statement in one sentence?
An if statement is a line of code that asks a yes-or-no question and runs the block beneath it only when the answer is yes.
Do I need to know maths to use an if statement?
No. You only need comparisons you already use in daily life: is this bigger, smaller, the same, or different.
What is the difference between an if statement and a loop?
An if statement runs a block at most once. A loop runs a block again and again until something changes. Most real programs use both, and loops usually contain an if.
Why does nothing happen when my if statement runs?
Because its condition was false. Print the condition itself, not the result, and you will usually see it is the opposite of what you assumed.