For Loops and Nested Loops in Python

In this article, we’ll discuss the for-loop a very important structure in Python, we’ll see how and when to use it. We’ll also learn about nested loops.

Sari Lakkis
6 min readMay 19, 2021

For this tutorial we have a small problem to solve, we want to ask our app user to choose a password but it must be more than 8 characters so if it is less than 8 we’ll ask him to enter it again. We want to solve it with what we know so far as an exercise on the loops and the if statement.

The Source code of this article can be downloaded from my GitHub Python repository.

Let’s start!

The For Loop

The for loop in Python is typically used for iterating over a sequence like a list or a string literal and in scenarios where we can know the number of repetitions we need to perform on our code.

In the example where we printed “I love Python” five times, we used the while loop and defined a variable that we used to control the number of iterations. For this kind of problem using the for loop is handier since we don’t have to manage the control variable although there is nothing wrong with doing that.

If we recall the while loop example, we used a variable to count to 5:

i = 1
while i <= 5:
print("I love Python")
i = i + 1

Now to write the same code using a for loop, we use the range() function to generate the sequence numbers and we iterate through them as we are saying: for each number in this sequence of numbers execute the code inside this loop.

The range() Function

This function will return a range of numbers, as its name implies, we specify how many numbers we want to have as a parameter. For example, in our loop, we want to repeat the print statement five times so we’ll use range(5).

The sequence returned starts from 0 by default and increments by 1 till it ends at the specified number which is five in our example with the five not being included (excluded), thus we have {0, 1,2,3,4}.

To iterate through this range, we use the keyword in so we say for example:

for i in range(5):

Writing the for-Loop Syntax

Now let’s write the above while-loop with a for-loop, also note the indentation for all the statements inside the for-loop the same way in while-loop or if-statement.

for i in range(5):
print("I love Python")

The above code will print the string literal: “I love Python” five times. The variable ‘i’, that could also be any variable name, will start with the first value in the range [0,4[ that i,s 0 and when the current iteration ends it will be automatically incremented by 1.

In the second iteration its value will be 1 and so on until it reaches the last number in the range which is 4 then the loop ends.

We can access I inside the loop so if we try to print its value instead of the string literal, we’ll have the numbers printed, please try it, I’ll wait, just write print(i) inside the for-loop.

This is the simplest way to specify a range(), however, the more general way is to specify the starting value as the first parameter so if we want to count from 1 to 5 we can write:

for i in range(1, 6):
print(i)

The above loop will print values from 1 to 5, remember that the ending number of the range is not included as if we are saying “i” ranges from 1 to strictly less than 6.

Also, we may specify the increment value other than 1 as the third parameter in the range() function. For example, if we want to print odd numbers only between 1 and 10, we want to start from 1 and ends before 10 and in each step or iteration we add 2 instead of 1, so we write:

for i in range(1, 10, 2):
print(i)

This will print the values 1, 3, 5, 7, 9.

Iterating Through Strings

If we are iterating through a string we are iterating through each character in this string, for example:

for x in "Pretty Code":

In each iteration x is the character from this string “Pretty Code” starting from the first to the last one.

Inside the loop, we can do anything with the character x like printing it or just moving through the string without touching it. For example, let’s count the characters in this string.

We will define a variable counter to hold the value for the number of characters we have and initialize it to 0 then in each iteration through the string we add a 1 to the counter. After the loop is finished, we print the result:

count=0
for x in "Pretty Code":
count = count + 1
print(count)

if you got 11 then you are right because the white space is also considered a character.

Back to Our Problem

We are set now to solve our problem, all we need to do is to read a password from the user, count the characters and if he didn’t get it right, we can politely ask him to do that again.

To do that we need a loop to repeat our part of the code that counts the characters in the password, so can we put a loop inside a loop? Yes, we can put a loop inside a loop as much as we want, this is called nested loops, sort like the inception movie where we have a dream inside a dream inside a dream. If you haven’t seen it, never mind I think it’s easier to understand nested loops.

Nested Loops

As we said a nested loop is a loop inside another loop, the inside loop called the inner loop will be executed for every iteration in the outer loop. For example, if the inner loop has 5 iterations that prints the string “I still love Python” and we place it inside a loop with 10 iterations, then the string will be printed 5 times for each iteration of the 10 iterations of the outer loop, so we got 5*10 = 50 times.

for k in range(10):
for x in range(5):
print("I still love Python")

Yes, I couldn’t count them too in the console, I got lost. So let’s count them as real developers.

counter=0
for k in range(10):
for x in range(5):
counter = counter + 1
print(counter)

And we’ll have 50 printed.

What loop to choose for our problem?

What do we choose as a loop as an outer loop in our problem that will keep asking the user to enter a password if it was less than 8 characters? For or while?

Since we don’t know how many times the user will set the password incorrectly so we’ll use a while loop.

Now what we’ll do is we’ll write the code as we are thinking loudly, so we define a Boolean variable that determines if the user has set the password correctly or not, and initially he off course hasn’t yet so its value is False. Then we repeat our code as long as it’s not set correctly, that simple and when it’s set correctly we change the value of the variable to true that way the loop is not repeated:

password_set= False
while not password_set:

We choose a meaningful name for our variable regardless of whether it’s too long, which is one of the first rules of writing clean code.

Inside the while loop we’ll read the password and count the characters using a for loop:

count = 0
password = input("Enter a password: ")
for x in password:
count = count + 1

then outside the for loop, we check the count if it’s less than 8, we inform the user of his fatal mistake then, else we want to change the password_set variable value to True to end the loop:

if count < 8:
print("Your password size must be at least 8 characters!")
else:
password_set= True

Finally, when we get out of the while loop, that means only one thing hat the password was set correctly so we can directly print that to the user or continue with our code logic:

print("Your password is accepted!")

The complete code:

password_set = False
while not password_set:
count = 0
password = input("Enter a password: ")
for x in password:
count = count + 1
if count < 8:
print("Your password size must be at least 8 characters!")
else:
password_set = True
print("Your password is accepted!")

Please try it and test with different passwords.

Conclusion

In this article we learned about for loops in Python and saw how to use them also we learned about nested loops and solved a small problem that included a nested for loop inside a while loop and also used what we had previously learned in previous articles like the if statement.

In the next tutorial, we’ll continue building our foundations in Python and we’ll discuss lists, an interesting topic, see you there!

--

--

Sari Lakkis

Professor | Consultant | Researcher. I give advice on strategy, design, and implementation of software that solves business problems to companies and startups.