22 min read
if and else
Make decisions with if and else — the colon, indentation, and the shop discount program next to its flowchart.
The if Statement
The discount rule (from the flowchart course)
Read this flowchart as text
- Terminator: Start (then → INPUT total)
- Input/output: INPUT total (then → total > 5000?)
- Decision: total > 5000? (Yes → total = total × 0.9; No → OUTPUT total)
- Process: total = total × 0.9 (then → OUTPUT total)
- Input/output: OUTPUT total (then → Stop)
- Terminator: Stop
discount.pyPython
total = float(input("Bill total (LKR): ")) if total > 5000: total = total * 0.9 print("10% discount applied") print(f"Amount to pay: LKR {total:,.2f}")Expected output
Bill total (LKR): 8000 10% discount applied Amount to pay: LKR 7,200.00
- if is followed by a condition and a colon (:).
- The lines that belong to the if are indented (4 spaces is standard). They run only when the condition is True.
- The first line that is not indented is after the if — it always runs.
Try Run again with 3000 in the Inputs box: the discount lines are skipped.
if … else
Pass or fail
Read this flowchart as text
- Terminator: Start (then → INPUT mark)
- Input/output: INPUT mark (then → mark >= 40?)
- Decision: mark >= 40? (Yes → OUTPUT "Pass"; No → OUTPUT "Fail")
- Input/output: OUTPUT "Fail" (then → Stop)
- Input/output: OUTPUT "Pass" (then → Stop)
- Terminator: Stop
pass_fail.pyPython
mark = int(input("Mark: ")) if mark >= 40: print("Pass")else: print("Fail")Expected output
Mark: 40 Pass
else (with its own colon) catches every case where the condition is False. Exactly one of the two blocks runs.
Flowchart to Python
| Reading a decision flowchart as code | |
|---|---|
Practice
Which line is correct Python?
More lessons in Python Programming · Next: elif and Nested if · Previous: Formatted Output
