Run code only when a condition is true, using if, a colon and an indented block.
About 25 minFirst steps4 exercisesFree
You will be able to
Explain what a condition is and why it evaluates to True or False
Write an if statement with a colon and an indented block
Predict which lines run when a condition is true and when it is false
Store the result of a comparison in a variable and use it as a condition
Every program you have written so far runs the same lines every time. Real programs react to their data. A warehouse system warns you only when stock is low. A checkout adds a delivery fee only when the order is small. A thermostat switches on the heating only when the room is cold.
All of these are decisions: do something if a situation is true, and skip it otherwise. In Python you make that kind of decision with the if statement.
Conditions are True or False
A condition is an expression whose value is either True or False. These two values have their own type, bool (short for boolean). Comparisons are the most common conditions:
Operator
Meaning
Example
Value
==
equal to
5 == 5
True
!=
not equal to
5 != 5
False
<
less than
3 < 10
True
>
greater than
3 > 10
False
<=
less than or equal to
10 <= 10
True
>=
greater than or equal to
9 >= 10
False
Notice that "equal to" is two equals signs. A single = assigns a value to a variable; == asks a question.
Try it: Change stock to 10 and run it again. Which lines change?
The if statement
An if statement has three parts:
if condition:
line that runs only when the condition isTrue
another line that runs only when the condition isTrue
line that always runs
The keyword if, then the condition.
A colon: at the end of that line.
An indented block: one or more lines pushed in by four spaces. These lines belong to the if.
Python uses indentation, not brackets, to decide which lines are inside the block. The first line that is back at the left edge is outside it, so it runs whatever the condition was.
A low-stock warning
stock =4if stock <10:
print("Warning: stock is low")print("Send a reorder request")print("Stock check finished")
Try it: Set stock to 25. The two indented lines are skipped, but the last line still runs.
Read it line by line:
stock holds 4.
Python evaluates stock < 10, which is True, so it runs the indented block: both warning lines print.
The unindented print is not part of the block, so it runs either way.
With stock = 25 the condition is False. Python skips the whole indented block and jumps straight to the first line after it.
Conditions become useful when the data is not fixed in the code. Combine input() and type conversion (from the previous track) with an if. Convert first: "9" < 10 is an error, because a string cannot be compared with a number.
Deciding based on what the user types
temperature =float(input("Body temperature in C: "))
has_fever = temperature >=38.0if has_fever:
print("Fever detected. Please see the nurse.")print("Reading recorded:", temperature)
Input given to the program: "38.6"
Try it: Change the input to 37.2 (or run it and type a value). Then try exactly 38.0: does it count as a fever?
Guided practice · ●difficulty 1 of 5 · about 4 min
Low-stock alert
A shop wants a warning when an item is running out. The starter reads the number of units in stock.
If there are fewer than 10 units, print Reorder needed.
In every case, print Check complete as the last line.
Examples:
Input
Output
4
Reorder needed then Check complete
25
Check complete
Keep the input() line as it is.
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Challenge · ●●difficulty 2 of 5 · about 6 min
Library late fee
A library charges 1.50 SAR per day for late books. The program reads how many days late a book was returned. Books returned early are recorded with a negative number, and on-time books with 0.
Create a variable fee that starts at 0. If the book is late (more than 0 days), set fee to the days late times 1.5. Then print the fee with two decimal places:
Fee: 4.50 SAR
Input
Output
3
Fee: 4.50 SAR
0
Fee: 0.00 SAR
-2
Fee: 0.00 SAR
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Debugging · ●difficulty 1 of 5 · about 4 min
Fix the free-delivery check
An online grocer, Basket & Co, offers free delivery on orders of 200 SAR or more. Their developer wrote this program, but pressing Run gives a SyntaxError before anything is printed.
Fix the program so that:
orders of 200 SAR or more print You qualify for free delivery,
every order then prints the total, for example Order total: 185.50 SAR.
Input
Output
250
You qualify for free delivery then Order total: 250.00 SAR
185.5
Order total: 185.50 SAR
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Edge cases · ●●difficulty 2 of 5 · about 5 min
Store a condition in a variable
An airline gate checks carry-on bags. A bag may weigh at most 7 kg. The program reads the bag's weight in kilograms (it may have decimals).
Create a variable too_heavy that holds the boolean result of the comparison (True when the bag is over the limit).
Print Too heavy: True or Too heavy: False using that variable.
If the bag is too heavy, also print Please check this bag in.
Input
Output
8.2
Too heavy: True then Please check this bag in
7
Too heavy: False
Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.
Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type
Output
Run your code to see its output, or Check to test it against the requirements.
The solution becomes available after you pass, or after all three hints and two checks.
Summary
A condition is an expression whose value is True or False (type bool); comparisons like <, >= and == produce one.
if condition: runs the indented block below it only when the condition is True.
Indentation decides which lines belong to the block; the first unindented line runs every time.
You can store a comparison in a variable and use the variable as the condition.
Always test values exactly on the threshold, and just either side of it.