Selection (IF)
Selection is how a program chooses between alternatives. Without it, a program can only work through the same steps every time; with an if statement it can react to the values it is given.
You need selection at any point where the next step depends on a value the program holds:
In this program the battery level decides which message the user sees:
battery = int(input("Battery percentage: "))
if battery <= 10:
print("Plug in now")
elif battery <= 30:
print("Battery low")
else:
print("Battery OK")Output when the user types 45:
Battery percentage: 45
Battery OK
An if statement is not just for the main program. Put one inside a loop and the condition is tested again on every pass, so the same decision can be made many times with different values. Put one inside a subprogram and the choice is made each time that subprogram is called. The keywords, the colon at the end of each condition line and the indentation rules are identical wherever the selection appears — only the values being tested change.
A well-written block has a single entry point — one place at the top where it begins — and a single exit point — one place at the bottom where it finishes. Nothing jumps into the middle of the block, and no branch leaves early, because anyone tracing the code would lose track of which line runs next. A subprogram follows the same rule: it is entered by its name, and it returns from one place at the end rather than from several.
A simple way to keep to this is to set a variable to a sensible starting value before the selection, change it inside a branch, then use it once afterwards:
weight = float(input("Parcel weight in kg: "))
postage = 3.50
if weight > 2:
postage = 3.50 + (weight - 2) * 1.20 # extra charge above 2 kg
print("Postage: " + str(round(postage, 2)))Output when the user types 3.5:
Parcel weight in kg: 3.5
Postage: 5.3
Both routes through the selection arrive at the same final line, so the block has one way in and one way out.
Edexcel GCSE Computer Science · Selection (IF)
Edexcel GCSE Computer Science · Condition Controlled Iteration (While Loops)