Programming Fundamentals
Along with sequence and iteration, selection is a fundamental programming construct. It allows a program to choose which block of code to run, depending on whether a condition is True or False.
A condition is a test that produces a True or False result. Selection checks the condition and uses that result to decide which block of code runs. Without selection, a program would follow the same path through its code every time it ran, whatever values it was given.
The condition can test a value entered by the user or a value the program has generated, such as a random number. For example, a museum guide program might ask which exhibition you want to visit and then use selection to print the room number for one particular exhibition.
exhibition = input("Which exhibition? ")
if exhibition == "dinosaurs":
print("Room 3")Output when the user types dinosaurs:
Which exhibition? dinosaurs
Room 3
In Python 3, the simplest form of selection uses if. The condition is placed after if, and the code that belongs to that condition runs only when the condition is True. If the condition is False, that code is skipped and the program continues with the next instruction after it. You need to be able to write selection yourself in a high-level language; for this course, that language is Python 3.