The first question your code ever asked
The problem...
Your code does exactly what you tell it. Every time. Without question.
You print a name — it prints the name. You calculate a number — it calculates the number. It doesn't care if the input makes sense. It doesn't care if something's wrong. It just runs.
That's a script. Not a program.
The idea!
What if your code could check something before acting?
What if it could say: "Only do this if the condition is true."
That's exactly what if does.
The syntax
if condition:
# code runs only if condition is True
Two things to notice:
The if line ends with a colon :. The code inside is indented — 4 spaces. That indentation tells Python: "this belongs to the if."
Your first if
temperature = 35
if temperature > 30:
print("It's hot outside.")
Python checks the condition: is temperature > 30 true?
Yes — so it runs the print. Simple as that.
What if the condition is false?
temperature = 20
if temperature > 30:
print("It's hot outside.")
Nothing happens. No output. No error. Python checks the condition, sees it's false, and skips the block entirely.
That's the power — code that only runs when it should.
Conditions you can use
x = 10
if x > 5: # greater than
print("big")
if x == 10: # equal to
print("exact")
if x != 7: # not equal to
print("not seven")
if x >= 10: # greater than or equal
print("at least ten")
Any expression that returns True or False works as a condition.
A real example
score = 85
if score >= 60:
print("You passed.")
Clean. Readable. Purposeful. Your code is no longer just calculating — it's making a decision.
Heads up!
- The
ifline always ends with: - The block inside must be indented — 4 spaces
==checks equality —=assigns a value. Not the same thing.- If the condition is false, the block is skipped — no error
The mindset shift
Stop thinking: "My code runs everything."
Start thinking: "My code runs what makes sense."
What you should understand now
ifruns a block of code only when a condition isTrue- The condition is any expression that evaluates to
TrueorFalse - The colon
:and indentation are not optional — they're part of the syntax - If the condition is false, Python skips the block and moves on