KS3 Computing/Selection
Selection
editSelection allows us to add an additional level of control to our programs. When we introduce Selection, the computer will only run an instruction IF a specified condition is true or false. Otherwise it will not run that code / instruction.
For example:
if age > 16:
print("You are allowed to drive")
The print command above will only run IF the specified condition (age > 16) is true. If it is not true (e.g. age is 13), that line of code will not run, it will be ignored.
if / else if / else
editYou can also have several alternative options using the IF-ELIF-ELSE constructs in Python (though all languages provide similar).
For example:
if age > 16:
print("You are allowed to drive")
elif age == 16:
print("You will be allowed to drive next year")
else
print("You are too young to drive, come back in a few years!")
You can nest IF statements inside one another to build even more flexibility.
Another example of Selection is called the CASE statement. We do not usually look at the Case statement at KS3.