Conditions
Why we need conditions
Analogy
- Before you left the house this morning you did something like this: if it looks like rain, take an umbrella, otherwise leave it at home.
- You checked something, got a yes or a no, and picked one of two actions.
- Every program you will ever write does exactly this.
- Up to now code has been a straight line where every instruction runs, top to bottom. Conditions are the moment a program starts making choices.
What is a condition?
Definition
A condition is a question that comes out true or false.
if runs a block when the answer is true and skips it entirely when it is false. else is the fallback that runs only when the condition was false.
Exactly one of an if and its else will run. Never both, never neither, and that guarantee is what makes them easy to reason about.
Chains, and the rule that makes them work
Real decisions rarely have two options, so you chain them. Python writes elif; C, Java and JavaScript write else if.
if marks >= 90: grade = "A"elif marks >= 75: grade = "B"elif marks >= 60: grade = "C"else: grade = "F"Here is the rule, and it matters more than anything else in this chapter:
Note
The computer checks the conditions from top to bottom, runs the first one that is true, and skips every remaining branch without even looking at it.
That is why the code above does not need elif marks >= 75 and marks < 90. If you reached the second line at all, the first must have been false, so the marks are already below 90. The chain remembers for you.
And it is why order matters enormously. Flip the chain around and a student with 95 gets a D, because the first condition caught them and nothing after it was ever considered:
if marks >= 40: grade = "D"elif marks >= 90: grade = "A" # this can never runWhen an if chain gives you the wrong answer, check the order first.
Truthy and falsy
Python, JavaScript and C let you put non-boolean things inside an if and decide for you what counts as true. In Python, 0, "", [] and None are all treated as false, and everything else as true.
if name: # true if name is not emptyif items: # true if the list has something in itIt reads nicely. It also causes one specific bug: if 0 is a valid value in your data, this check wrongly rejects it. When zero is a real possibility, compare explicitly with if count != 0.
Also worth a note: writing if is_valid == True works but is clumsy. is_valid is already true or false, so just use it.
Flattening nested conditions
An if can live inside another if, but deep nesting gets unreadable fast. Three levels is usually a warning sign.
The fix is a guard clause: handle the exceptional cases first, get them out of the way, and let the main logic sit flat at the bottom.
if not is_logged_in: show_login_page() return if is_admin: show_admin_panel() return show_user_panel()Same behaviour as three nested if statements, far easier to read. This is a habit that separates messy code from clean code and it costs nothing to learn now.
The one-line version
When a whole if/else exists just to pick between two values, there is a shorter form:
status = "Adult" if age >= 18 else "Minor"Use it for short, simple choices. Do not chain three of them together - at that point an ordinary if is kinder to whoever reads it next.
Braces, and a famous bug
Python uses indentation, and the spaces are the syntax rather than decoration. C, Java and JavaScript use braces, and they let you skip them when the body is a single line.
Watch out
Do not skip them.
if (x > 5) print("big"); print("really big"); // this always runsThe indentation says both lines belong to the if. The compiler disagrees, because without braces only the first line counts. This exact bug shipped in real Apple security code and became famous as "goto fail".
Mistakes to watch for
Watch out
=instead of==. In C and Java,if (x = 5)assigns and is always true.- Wrong order in a chain, making later branches unreachable.
- Forgetting the
else, so an unexpected input silently does nothing at all. - Writing
if (a == 1 or 2). This does not mean what you think. Writeif a == 1 or a == 2. - Using
andwhere you meantor. Read the condition aloud to catch it.
Quick recap
- A condition is a question that answers true or false
ifruns a block when true,elsecovers everything else- A chain runs the first true branch and skips the rest, so order is logic
- Many languages treat
0, empty text and empty lists as false - Deep nesting is a smell. Guard clauses flatten it
- Use braces in C-style languages even for one line
Key takeaway
An if chain runs the first branch that says yes and ignores the rest, which is exactly why the order you write them in is the logic.