So far a program runs every line in order, always. But sometimes it must decide: "if the student read 100 books, give a badge". That is a condition.
books = 100
if books == 100:
print("Reading Champion Badge!")Reading Champion Badge!
| Part | Meaning | In the example |
|---|---|---|
| After if | The condition | books == 100 |
| End of the line | A required colon | : |
| The indented line below | What runs if the condition holds | print("Reading Champion Badge!") |
A condition is True or False
== asks: are the two values equal? The answer is one of two values: True or False. You can print it:
books = 100 print(books == 100) books = 80 print(books == 100)
True False
An if runs what is under it only when the condition is True. When it is False, it skips it as if it were not there.
= assigns (put the value in); == compares (are they equal?). Writing if books = 100: is an error.Indentation
Python knows which lines belong to the if by their indentation: 4 spaces at the start of the line. A line that is not indented does not belong to the if, so it always runs:
books = 80
if books == 100:
print("Reading Champion Badge!")
print("Well done!")
print("See you next week")See you next week
Forgetting the indentation causes an error:
books = 100
if books == 100:
print("Reading Champion Badge!")IndentationError: expected an indented block after 'if' statement on line 2
: at the end of the if line, and forgetting to indent the next line.Practice
Complete the condition line: if books equals 100, print Reading Champion Badge!
books = 100
___
print("Reading Champion Badge!")Press Run to see the result. Assign 100 to english; if english equals 100, print Get a reward.
Press Run to see the result. Assign 100 to num; if num equals 100, print Correct.
Press Run to see the result. Assign 80 to math, then print the result of the comparison math == 80 (it should show True).
Press Run to see the result. The program has two mistakes that stop it running. Fix them so it prints Free entry then Enjoy the museum.
Hint
Check the comparison sign and the end of the if line.age = 6
if age = 6
print("Free entry")
print("Enjoy the museum")Press Run to see the result. Assign "nile2026" to password. If password equals "nile2026", print Welcome back. At the end (outside the if) always print Goodbye.
Press Run to see the result. Key points
- Shape:
if condition:, then the commands that belong to it on the next lines, indented 4 spaces. - A condition is
TrueorFalse; if runs its block only when it is True. =assigns;==compares.