Lessons › coding and computer science · taught by Leo
If statements in code: how conditions control flow
Learn what if statements do, how conditions work, and why indentation matters in Python.
Learn this with Leo, freeA voiced lesson with a live whiteboard, quizzes and a tutor you can call, at tutelage.appWhat an if statement does
An if statement is a choice in code. When the condition is true, one block runs.
If it is false, that block is skipped. The program keeps going from the next line.
Big idea: condition controls flow
An if statement checks a condition first, then decides whether to run a block.
Think of it like a door that opens only if the condition is true.
The condition is a question the computer can answer with true or false.
Then the code follows the answer.
Predict: true or false
If x = 5, what does this condition give? x > 3
- true
- false
Show answer
true: Yes. Five is greater than three, so the condition is true.
Write an if block
Here is a tiny example. First we check whether x is greater than three.
If that is true, the indented line runs.
Because x is five, the print line happens.
Quick check: what comes next
In Python, what should you do right after `if score >= 90:`?
- Indent the code block under it
- Put a semicolon at the end
- Write `else` immediately
Show answer
Indent the code block under it: Correct. The next lines must be indented to belong to the if block.
Why indentation matters
Indentation tells Python which lines are controlled by the if statement.
Python uses spacing to group the block.
That is why the indented lines belong together.
No indent means the line is outside the if.
The if flow
This is the whole flow. First the condition is checked.
If it is true, the block runs.
If it is false, the block is skipped and code continues.
Either way, the program moves on after the if.
Watch out for assignment
A very common mistake is using one equal sign in a condition.
Double equals means compare. One equals means assign a value.
Your turn: pick the block
What is the correct result of this code idea? If temp < 0, show 'cold'. Temp is -2.
- It shows 'cold'
- It shows nothing
- It changes temp to 0
Show answer
It shows 'cold': Yes. Negative two is less than zero, so the if block runs.
Remember the if checklist
Here is the checklist you can use alone.
Read the condition and decide true or false.
Then run the indented code only if it is true.
If it is false, skip that block and keep going.
Recap: if statements
An if statement is a gate: true opens it, false leaves it closed.
The condition is the question.
The indented block is the action.
True means go, false means skip.