9.3. Selection StatementsΒΆ
Selection statements are used in programming to select particular blocks of code to run based on a logical condition. The primary selection statements in Python are:
if
else
elif
try
except
So far in this text, all of the Python code has either been strictly linear or linear and include functions. A strictly linear program is a program that runs top to bottom. Every line of code in a linear program is executed. In a linear program with functions, the program still runs head to base, but the program takes side excursions to execute functions on the way down.
If this next couple chapters, you learn to write programs non-linearly. Non-linear programs do not run every line of code top to bottom. In non-linear programs, sections of code may not run based on selection statements like if and try. Non-linear programs can include loops. Inside loops are sections of code that run multiple times. Loops are defined by repetition structures like for loops and while loops.
To start our discussion of non-linear programs, we will begin with if statements.