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

Loops and statements in Python: A deep understanding (with examples)

When they appear to be understood, there is something more

Photo by Nick Rickert on Unsplash
Photo by Nick Rickert on Unsplash

When studying Data Science, the first step is to learn to program, and one of the very first topics one learns is loops and statements. Well, actually I’m not such a genius in programming (I’m moving to an intermediate level 🙂 ), but loops really have tested me. They seem to be so easy, so understandable…that maybe you can say "ok, this is really obvious!". Also, this can be due to Python itself, since it has been invented to be easily understood by humans. So, I want to go a little deep in explaining loops and statements so that we can see, with some examples, how much there is to understand behind them.


Loops in Python: the "for" loop

First of all, I want to explain is the "for" loop. Let’s make a simple example to understand the Basics. Suppose we have a list of four numbers and I’m calling it "numbers"; it is defined like that:

numbers = [2, 3, 5, 7]

I want my Python script to print all the numbers in my list. To do it I can use a simple "for" loop like that:

numbers = [2, 3, 5, 7]
for number in numbers:
    print(number)

and the result is:

2
3
5
7

Let’s analyze a little deeper these lines of code. First of all an important thing: in for loops we use auxiliary variables. In this case, the auxiliary variable is "number"; in fact, I’ve defined the list called "numbers" and you do not see any variable defined as "number"; so the "number" auxiliary variable is used directly in the loop, and I define it while I code the loop.

Now, let’s see an example that can be useful to think about how a for loop really works because with the above example one may think has understood, but maybe…not!

Let’s define a list and use it to print something. For example:

my_list = [1,2,3,4,5]
for x in my_list:
    print ("cool")

this is the result:

cool
cool
cool
cool
cool

well…one should immediately ask himself: "dear my friend Python, I’ve asked you to print "cool" just one time; would you, please, tell me why in the world you’ve printed it 5 times??"

This is the right question showing one has not understood the for loops with the prior example, but it is a useful question to think over the for loops and get a deep understanding.

I’d like to think of for loops like the electrical current or a fluid circulating in an object. In this case, the object is a list and our friend Python (you can even think of it as a snake 😀 ) "circulates" in the list and tries to do what you’ve asked with your code; in this case, it finds 5 numbers (the list is made of 5 numbers) and it prints "good" for every value in the list: this is how the for loop works.

The following image may help you visualize how a for loop works.

A visual representation of how the for loop works. Image by the Author.
A visual representation of how the for loop works. Image by the Author.

Statements in python: if-else and if-elif-else statements

Now, let’s go through the "if" statement. The "if" statement is not properly a loop. It is a statement through which we can say that a condition must be true; if not, we can say something else (using the "else" statement). Let’s see a simple example of the if-else statement.

x = 2
if x > 0:
    print("x is greater than 0")
else:
    print("x is negative")

And…guess what? The result is:

x is greater than 0

Again, very easy and one may be sure has understood the if statement.

Let’s see something a little more difficult. Now, we want to use the if-elif-else statement in which the code tests the conditions "if" and "elif" (which means "else, if"); if those are false, it testes the else.

x = 1
if x == 1:
    print(x)
elif x == 3:
    print(x)
else:
    print("error")

Of course, the result of this code is:

1

This is very very simple. I impose x to be 1, so the only true value can be the one imposed by the "if" statement. And, again, one may think has understood everything. But the real beauty comes when trying to put it all together.

Loops and statements in python: if-elif-else statement nested in for loops

Let’s say we have another list of numbers from 1 to 5, and we want to iterate through it, giving some conditions with the if-elif-else statement. To do this, I we have to nest a if-elif-else statement in a for loop. What does it mean? It means that our "python will circulate" (remember the image above? 😀 ) through the list testing some conditions, which are defined by the if-elif-else statement. And the code will print something when the condition is matched ("if" or "elif"); when not ("else"), it prints something else.

For example:

my_list = [1,2,3,4,5]
for x in my_list:
    if x == 1:
        print(x)
    elif x == 3:
        print(x)
    else:
        print("wrong numbers")

and the result is:

1
wrong numbers
3
wrong numbers
wrong numbers

If we have understood how the for loops and the if-elif-else statement work, the result is obvious: our auxiliary variable (called "x") goes through our list (called "my_list") and testes the given values for each number, imposed by the if-elif-statement.

Firstof all, x finds the value 1 in the list. It matches with the "if" statement, so the code prints "1" Then x finds 2; it does not match with any of the imposed values (1 for the if and 3 for the elif statement) so the code prints the "else" condition, which is "wrong number". Then it goes to 3; it finds the match with the elif statement and prints 3. Then it goes through 4 and 5 and since it doesn’t find a match it prints "wrong number", imposed by the else condition.

As we have seen: when for loops and statements appear to be understood, there is something more, deeper…and I hope this article can be useful to students with some doubts on these topics!


Need content in Python to start or boost your career? Here are some of my articles that can help you:

Python:


Consider becoming a member: you could support me and other writers like me with no additional fee. Click here to become a member.


Related Articles