Two ways to go
Run some lines only when a condition is true, and other lines when it is not. About 8 minutes.
If it rains, take an umbrella
You make small decisions all day: if it is raining, take an umbrella. If it isn't, leave it at home. Code can decide in just the same way.
An if checks a condition, which is a question with a true or false answer. When the answer is true, the lines inside the if run. When it is false, they are skipped. Python marks the inside lines by indenting them. The other languages wrap them in curly brackets.
if price >= 500:
price = price - 50Else: the other path
Often you want something to happen either way, but a different thing. An online shop gives free delivery above 500 rupees, and charges 40 below that.
Add an else after the if, and you get two paths. The computer checks the condition. If it is true it runs the first path, and if it is false it runs the second. Exactly one of them runs, never both and never neither.
if total >= 500:
shipping = 0
else:
shipping = 40- total
- 300
The shop checks the condition: is the total at least 500? The total is 300, so the answer is false.
total is 300. The code says: if total >= 500, then shipping = 0, else shipping = 40. What is shipping afterwards?
- A40
- B0
- CBoth lines run, so it ends as 40
Show the answer
40. 300 is not at least 500, so the condition is false and the else path runs.
Discount price
A shop gives 10% off any price of 500 or more. The discount is rounded down to a whole number. Return the price to pay.
price = 600 → 540
0 ≤ price ≤ 1,000,000