The world’s leading publication for data science, AI, and ML professionals.

Python for beginners – Control Flow

You wanted to learn something about fi-else conditionals or loops? Look no further!

Recently I’ve started a Python programming beginner oriented series of articles. We’ve already covered topics related to starting your Python journey and last time we’ve worked with operators. Today we will continue our journey, and tackle the topic of Control flow.

Or as Jake VanderPlas in "A Whirlwind Tour of Python" would say: "Control flow is where the rubber really meets the road in programming."

I’ve decided to split the article into several parts to facilitate the learning process. The parts are as follows:

  • Introduction
  • Conditionals or Conditional Statements
  • Loops
  • for
  • while
  • Controlling loops with Breaks & Continues
  • break
  • continue
  • Conclusion

Happy reading! 🙂

Photo by Filip Mroz on Unsplash
Photo by Filip Mroz on Unsplash

Introduction

First and foremost, what is Control Flow? Well, in simple terms it is the order in which certain operations are executed. Let’s take a simple example, say we want to measure the air temperature outside. What do we need to do? First we take the thermometer, then we open the door, we go outside, we close the door, we find a place in the shadow, we measure the temperature, we write it down, etc.

Similar, in programming, if we want to do a specific task or operation, we need to do simple smaller steps. These steps can for example include decision making or repetition of a task for a given number of times.

Let’s say we wanted a script that according to some criterion executes differently, for example, if we measured the air temperature is 3°C it prints out "It’s cold outside", but if it’s 21°C it prints out "It’s warm outside". In this case, some condition is checked, and according to the condition, a task is executed (a certain statement is printed out).

Or let’s say we wanted to convert the measured air temperature on each weekday in degrees Celsius to Fahrenheit. Then we need a script that takes the measured temperature on each weekday and executes the following the formula:

*(°C 1.8) + 32 = °F**

This means we do a similar task for a known number of times, precisely seven times. We take seven numbers and multiple each by 1.8 and add 32 to it.

Let’s now see some of the examples in more detail and with code provided. 🙂


Conditionals or Conditional statements

Conditional statements, or often called if-then statements, allow us to execute a piece of code depending on some condition (Boolean condition). Conditional statements in Python are:

  • Simple if
  • if-else
  • nested if
  • if-elif-else

The keywords (symbols) to apply a conditional statement are if, elif, else and a colon (:). It’s important to indent the new line after a colon.

Simple if statement:

Let’s visualize the simplest case.

by author
by author

If the if statement expression evaluates to True, then the indented code following the statement is executed. If the expression evaluates to False then the indented code following the if statement is skipped and the program executes the next line of code which is indented at the same level as the if statement.

We declare the variable x to be 10. We check if x is greater than 5, since this statement is True (10 > 5), the print command get’s executed, and the sentence "X is greater than 5!" is printed out.

What about the case when this statement is not True? Then, this script would do nothing.

by author
by author

If we wanted a script that does something when the statement is False we need to modify it a little.


if-else statement

As mentioned above, this statement allows us to add a second possibility to the script, what to do when the condition is False. Let’s visualize this case.

by author
by author

The indented code for the if statement is executed if the expression evaluates to True. The indented code immediately following the else is executed only if the expression evaluates to False. To mark the end of the else block, the code must be unintended to the same level as the starting if line.

by author
by author

The above code checks if the entered temperature is above 15, if the statement is True, it prints out that we don’t need a jacket, but if the air temperature is bellow 15, the script suggests to take a jacket.

Now we know that if it’s above 15 °C we don’t need a jacket, but what shirt to take, short or long sleeved? In order to answer this question with our script we need to use a nested if statement.


nested if statement

Basically that’s an if statement inside an another if statement. Let’s see is visualized, to get a better understanding.

by author
by author

As before, the code checks if the air temperature is above 15°C, if the statement is True, it suggests that we don’t need a jacket. Next it checks if it’s bellow or equal to 20°C, if that’s True, it suggests a long sleeved shirt. If that’s False, so it’s warmer than 20°C, it suggests a short sleeved shirt.

by author
by author

This example can also be solved using a if-elif-else statement. Let’s see how.


if-elif-else statement

The elif keyword can be thought as else if, we used it if we want a more distinct division between if and else. The Python elif statement allows for continued checks to be performed after an initial if statement. An elif statement differs from the else statement because another expression is provided to be checked, just as with the initial if statement.

by author
by author

If the expression is True, the indented code following the elif gets executed. If the expression evaluates to False, the code can continue to an optional else statement. Multiple elif statements can be used following an initial if to perform a series of checks. Once an elif expression evaluates to True, no further elif or the else statement is being executed.

by author
by author

The code first checks if the air temperature is bellow 15°C, if True, it suggests taking a jacket. If False, it checks if it’s bellow or equal to 20°C, if True, it suggests a long sleeved shirt. If both statements are False, the else statement gets executed, and it suggests taking a short sleeved shirt.


Loops

Or often referred as repetition statements, are used to repeat a block of instructions. In Python, there are two types of loops:

  • for loops
  • while loops

for loops

For loops are used when we iterate over a sequence of data, i.e. a list, tuple, dictionary, string etc. They are used when we iterate for a known (or desired) number of times, since we know how many elements there are in a list or string. The keywords to apply a for loop are for and in.

by author
by author

This visualization shows a simple for loop workflow. We initialize a sequence (list, string, tuple…), the loop checks if the item is the last, if True the loop stops, if False the code gets executed and the loop repeats on next item in the sequence. Until the code gets executed for the last item, the loop will repeat itself.

Let’s see an example. We will calculate air temperature in Fahrenheit for an week of Celsius degrees measurements. Therefore we declare a python dictionary which holds the weekday as key and the measured daily air temperature as value.

by author
by author

When we loop over a dictionary we use the .items() method, which returns the k (key) and v (value). Next, we create a new variable called temp_f which holds the calculated temperature in °F. To print out the calculated temperatures we use the string format method. This method converts the given variable to a string and allows us to use it in a sentence. We have to use curly braces {} on the wanted location in the sentence.

"The air temperature on {} was {:.2f}°F."

After the sentence (string), notice the quotation marks, we apply the .format () method. We provide the variables we want to print out in the sentence, in this case, the k (weekday) and temp_f (calculated temperature in Fahrenheit). The ":.2f" means we convert the calculated value (float) to a string, with two decimal places after the decimal point. Check the official sites for more insights.

.format(k, temp_f)

The great thing about loops is, we need to do this once, but the loop will repeat for each weekday and execute the wanted task.


while loops

In Python, while loops are used to iterate until a certain condition is satisfied. Basically, the loop is executed as many times as the condition remains True. when if becomes False, the loop stops. Let’s clarify this statement with a simple visualization.

by author
by author

A simple while loop works as follows. The argument gets evaluated, according to a expression, the code gets executed until the argument is evaluated as True. When it becomes False, the loop stops.

VERY IMPORTANT: In every step of the while loop we need to change the argument in order to avoid an endless loop.

Let’s see an example with counting days.

by author
by author

We start with day equal to one. The argument (value of the variable day) is checked if it’s lower or equal to eight, if True, it gets printed out. After printing we increase the value of the variable day by one to avoid an endless loop. If we hadn’t increased day by one in each loop, the variable day would have stayed equal to one, and so less than eight and the loop would have been endless.


Controlling loops with Breaks and Continues

The break and continue statements help us fine tune our loops and their execution.

  • The break statement breaks-out of the loop entirely
  • The continue statement skips the remainder of the current loop, and goes to the next iteration

Both of them can be used in both for and while loops.

break statement

by author
by author

The break statement is used in situations where we want to break out of the loop, even if the condition has not become False or we have iterated over the entire sequence. Also, if break is used, any following else blocks are not executed.

Let’s take a simple example with our air temp measurements in a week. Let’s say we want to stop printing out temperature values, if the air temperature is equal to or higher than 18°C.

The code prints out temperature values, when we reach Friday, with a temperature of 18.9°C, the loop breaks, and stops.

by author
by author

The code prints out temperature values, when we reach Friday, with a temperature of 18.9°C, the loop breaks, and stops.


Continue statement

by author
by author

The continue statement is somewhat similar to the break statement, but instead of breaking the loop, it will start the next iteration. The visualization on the left help us get a clearer understanding.

Let’s say we have a case where we want to print out temperatures but exclude those that are lower than 15°C. This would mean, we print out all except the values for Thursday. For such a task we would use a continue statement. So we loop through the dictionary, and when we reach a temperature that is lower than 15°C, the continue statement is activated, and it avoids the execution of the print statement, instead, it jumps to the next iteration. Let’s se the code.

by author
by author

The continue statement is great for discarding or excluding tasks, where our goal is to avoid a value, group of values or a certain condition.


Conclusion

Control Flow is one of the most important topics related to programming, and it certainly differs an useful from an useless code. Everywhere from simple data exploration, to "State-of-the-Art" Neural Networks, we deal with Control Flow of some kind.

There are numerous examples related to Control Flow, but with those simple ones presented here, we saw the possibilities Python offers. My idea was to keep the examples as simple as possible. The best is always to start simple, and work towards more complex examples.

As we continue our journey we will encounter more complex examples, and see even more interesting approaches related to Control Flow and everything else we learnt so far.


For any questions or suggestions regarding this article or my other articles on Medium, feel free to contact me via LinkedIn.

Thank you for taking the time, Cheers! 🙂


Related Articles