The Idea of Control Flow

Read Time:2 Minute, 39 Second

“Control” is the rule or order given to someone or something’s behaviour. “Control flow” in the context of Computer Science is the order of statements executed when a program is running. Code without control flow is just simply “code” literally, and it’s hard to put into practice. It is the building block of an algorithm.

The terms we always hear of “if-then”, “if-else”, “for loop”, and “while loop” are all control flows in programming. With them, we can turn our code into small programs and make them live.

The if statement will examine the boolean expression we put behind it; if the statement is True, the code after it will be executed; if it’s False, nothing will happen, or something else will be done instead. To have a better idea, let’s consider how we determine if an integer is an even or odd number. By definition, a number can be divided by 2 and the remainder is 0, which is an even number. Otherwise, it is an odd number.

Fig 1. Even or odd

Or we can think of a situation where the lamp in our bedroom doesn’t light up when we try to turn it on.

Fig 2. Lamp does not light

Our first instinct is to check whether the lamp was plugged; if not, voila! Problem solved. If the answer is yes, we have to check further if the problem is with the light bulb. If it is, we could fix it by simply replacing a new light bulb. If unfortunately not, we might have to find a technician who will help us repair the lamp.

These two simple flow charts have demonstrated how control flow works in programming. Machine uses this binary logic (1 and 0) to decide what to do in a step-by-step manner, even when dealing with more complicated operations.

Now I can write a simple program called “Magic 8 Ball” with the use of “if”, “elif”, and “else”. This program was taught as a mini project in Cocademy: Learn Python 3 course. I have made some tweaks to make it more fun.

“The Magic 8 Ball is a plastic sphere, made to look like an oversized eight ball, used for fortune-telling or seeking advice. It was invented in 1946 by Albert C. Carter and Abe Bookman and is currently manufactured by Mattel. The user asks a yes-no question to the ball, then turns it over to reveal an answer in a window on the ball.” (Wikipedia).

The program will ask your name and the yes-no question that you want to raise, and it will reply to you with an answer randomly selected. The code after the if statement will be run first. If the condition is False, the code after elif will be run following. If all conditions do not match, the else statement comes in. The code is as follows.

When you ask a question you will see something like below:

Source: