Control Flow-Python Loops

Michel
4 min readJan 1, 2021

--

Sometimes when need to repeat an operation more than once. Writing a code more than once is not considered good practice in programming; therefore, the creators of the computer have added functionality so that we can command the CPU to perform a jump to the next index in the memory when needed. In high-programming languages like Python, loops allow us to repeat blocks of code. There are two types of loops, for-loops, and while-loops.

Let’s first take a look at for-loop which we can use to iterate over an iterable! However, iterable is an object that can return one of its elements at a time. The iterable object can be a sequence type like String, List, and Tuples as well as a non-sequence type like Dictionaries and Files. For example, let’s consider the following loop which iterates over a list, converts all uppercase characters to lowercase, and prints it.

countries = ["UNITED KINGDOM", "CANADA", "GERMANY", "FRANCE", "SPAIN"]for country in countries:
print(country.lower())

The output:

united kingdomcanadagermanyfrancespain

We can identify that this is a for-loop when we see the for keyword at the beginning. “countries” is the iterable list and “country” is the variable that represents the element that the loop is processing over the list. Since “country” is a String object, then it has implemented methods inside it such as lower() and upper() which convert a character either to lowercase or uppercase, therefore, we can use these methods in the for-loop body to apply them on each element. You can name the iteration variable whatever you want, but you should give a meaningful name.

We can also use for-loops to create a new list and modify lists. To create a new list, we can create a new variable and assign it to an empty list, then in the loop body, we use the append method to add the elements we want in the new list. for example:

countries = ["UNITED KINGDOM", "CANADA", "GERMANY", "FRANCE", "SPAIN"]new_list = []for country in countries:
new_list.append(country.lower())
print(new_list)

The Output is a new list with lowercase string elements

['united kingdom', 'canada', 'germany', 'france', 'spain']

To modify a list, we know that lists are mutable which means that we can change the data inside the current list we are using. For example:

countries = ["UNITED KINGDOM", "CANADA", "GERMANY", "FRANCE", "SPAIN"]for index in range(len(countries)):
countries[index] = countries[index].lower()
print(countries)

The Output is the same list after modifications:

['united kingdom', 'canada', 'germany', 'france', 'spain']

In the example above, I have used the range method which creates a new iterable object of type list. This method is useful as we can create a list with a specified length, and we can also specify where we want to start with the list and the step between each number (range(start, stop, step)) However, since we have only provided the length of the array “countries”, then the remaining arguments will have the default value of 0. In the body of for-loop, we have assigned each element of the list that represents that current index of the loop to a new value which is “countries[index].lower()”. At the end of the code, we print the modified list ‘countries’.

The second type of loops is the While-loop which also iterates over an iterable object until a certain condition met. While-loop serves the same functionality as the for-loop. For example:

countries = ["UNITED KINGDOM", "CANADA", "GERMANY", "FRANCE", "SPAIN"]index = 0while index < len(countries):
countries[index] = countries[index].lower()
index += 1
print(countries)

This is the same example I showed before, but I used While-loop instead. Note that sometimes while-loop can be more concise and faster since we have not used the range method to achieve the goal. The difference is that in While-loop, we need to define a variable that represents the starting point of the loop (The index variable) then we to add a line of code to increment this variable after each iterate. However, we should note that if we don’t increment this variable, the program will run infinitely.

To increment a variable in Python, we can use one of the following ways:

index += 1index = index + 1

While-loop is a dangerous type of loop because it can easily run into an infinite loop if we are not aware of what we are doing, but it’s useful if we want to prompt the users until they type a specific command. For example

In the example above, we used while True, so that the program can run until the user exit the program with the commands that I have added.

--

--

Michel
Michel

No responses yet