From the previous tutorials in this series, you now have quite a bit of Python code under your belt. Everything you have seen so far has consisted of sequential execution, in which statements are always performed one after the next, in exactly the order specified.
But the world is often more complicated than that. Frequently, a program needs to skip over some statements, execute a series of statements repetitively, or choose between alternate sets of statements to execute.
That is where control structures come in. A control structure directs the order of execution of the statements in a program (referred to as the program’s control flow).
Here’s what you’ll learn in this tutorial: You’ll encounter your first Python control structure, the if statement.
In the real world, we commonly must evaluate information around us and then choose one course of action or another based on what we observe:
If the weather is nice, then I’ll mow the lawn. (It’s implied that if the weather isn’t nice, then I won’t mow the lawn.)
In a Python program, the if statement is how you perform this sort of decision-making. It allows for conditional execution of a statement or group of statements based on the value of an expression.
The outline of this tutorial is as follows:
First, you’ll get a quick overview of the if statement in its simplest form.
Next, using the if statement as a model, you’ll see why control structures require some mechanism for grouping statements together into compound statements or blocks. You’ll learn how this is done in Python.
Lastly, you’ll tie it all together and learn how to write complex decision-making code.
Ready? Here we go!