Getting started with control flow
By themselves, computers are pretty dumb. They don’t know what to do or how to reason independently. In this part of the chapter, we’ll learn how to instruct a computer to make decisions based on the data it receives.
Computers do exactly what we tell them to. As you’ll come to understand while learning to code, this is a blessing and a curse at the same time. It means that we must be very precise in formulating what we desire from them. Luckily, there are multiple structures to provide these instructions.
The if statement
The easiest way to make decisions, on a computer or otherwise, is by using an if
statement. An if
statement looks like this: If the player’s health is below zero, end the game. We could generalize this as if a certain condition is true, perform an action. The code to make this decision could look like this:
if number_of_lives < 0: print("You died!")
This code...