Lesson 4 of 21 · 2 min
if Statement — Making a Single Decision
The WHY — Why if Statements?
Your program needs to respond differently in different situations. A grade calculator should print "Pass" for a score of 70 and "Fail" for a score of 30 — it cannot do the same thing for both. The if statement says: "Only run this code IF this condition is true."
Basic if Syntax
score = 75 # a student's exam score
if score >= 60: # check: is score 60 or higher?
print("You passed!") # this line ONLY runs if the condition above is True
print("Congratulations!") # indented code = "inside the if block"
Output: You passed! Congratulations!
The colon : after if score >= 60 is required. Do not forget it.
Indentation (spaces before the code) is how Python knows what is "inside" the if block. Use exactly 4 spaces (or 1 Tab). This is unique to Python — other languages use curly braces {}.
score = 45 # a failing score this time
if score >= 60: # check: is 45 >= 60? NO — condition is False
print("You passed!") # this line is SKIPPED because condition was False
print("Exam complete.") # this line is NOT indented, so it runs regardless
Output: Exam complete.
