Coding for All
Lesson 9: If Statements
If Statements Only run code when a condition is true.
1age = 10
2if age > 8:
3 print("You are older than 8")
Terminal
$ python3 main.py
You are older than 8
Every line, explained
age = 10
This creates a variable: a named box that stores a value. In Python you just write name = value: the = stores the value on the right into the name on the left. No special type word, no semicolon; Python keeps it simple.
if age > 8:
if checks the condition after it. Two things to notice: the line ends with a colon :, and the lines that belong to the if are indented 4 spaces underneath. Python uses indentation to know exactly which code is "inside" the if. If the condition is True the indented code runs; otherwise Python skips it. (The editor indents for you here; in a real editor you would type the 4 spaces.) Here > means "greater than", and 10 > 8 is True, so the indented line runs.
print("You are older than 8")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. This line is indented 4 spaces, which is what makes it belong to the if above.