if statement
An if runs a block of code only when its condition is true.
Used in 123 lessons of the course, from 00.01.
An if is a decision. You write if, a condition, and a colon. Below it, indented, goes the block that runs only when the condition is true.
If it is false, Python skips the whole block and continues with the next line that has no indentation.
The condition is usually a comparison (x > 3) or a membership test (key in GLOSSARY). Python accepts any value and treats it as true or false. An empty list, an empty string, 0 and None count as false.
The indentation is not decoration: it is how Python knows which lines belong to the if.
if key in GLOSSARY:
print("found")
In the course you will mostly see it checking whether something exists before using it, as in lesson 00.01.
Reach for it when: a piece of code should run only under a certain condition, such as a key existing or a value not being empty.
Examples
Common mistake
x = 5
if x = 5:
print("five")Why: A single = assigns; it does not compare. Inside an if Python expects an expression.
How to write it: Use == to compare: if x == 5:.
Common mistake
x = 5
if x > 3:
print("big")Why: The block under the colon needs indentation so Python knows it belongs to the if.
How to write it: Indent the line with 4 spaces: print("big").
