3

Understand Loops in Python with One Article

 3 years ago
source link: https://towardsdatascience.com/understand-loops-in-python-with-one-article-bace2ddba789
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Understand Loops in Python with One Article

After reading this article, there will be no chance Loops will ever throw you for a Loop

Computers are great at performing repetitive tasks over and over, as they never “get bored” or make mistakes. A simple calculation requested to a computer could be performed one or a thousand times, and the first result will be as accurate as the last one. This is something humans are not capable of guaranteeing.

Being able to delegate the automation of routinary tasks to computers is an invaluable skill which every programmer should master in order to improve their coding skills and code accuracy.

The number of tasks available to perform with the help of loops ranges from copying files to a group of computers on the network, sending personalized emails to certain users or verifying that a process is still running.

It doesn’t matter the complexity of the task, the computer will perform it as many times as you tell, which more importantly, leaves you more time to spend with more interesting activities.

In Python, Loops can be me implemented in three ways:

  • While” Loops
  • For” Loops
  • Recursion

During this article, I’ll explain these techniques considering that each one takes a slightly different approach. You’ll learn how to write the code and how to understand when to use one technique instead of the others.

Table of contents:

1. While Loops (4 min read)

2. For Loops (4 min read)

3. Recursion (3 min read)

1. While Loops

This technique instructs the computer to continuously execute a code based on the value of a condition. It begins with the keyword while, followed by a comparison to be evaluated, then a colon. On the next line is the code block to be executed, indented to the right. Similar to an if statement, the code in the body will only be executed if the comparison is evaluated to be true.

What sets a while loop apart, however, is that the code block will keep executing as long as the evaluation statement is true. Once the statement is no longer true, the loop exits and the next line of code will be executed.

Take a look a the following example:

Image for post
Image for post

Let’s go through each line of code inside this loop:

  1. In the first line we’re assigning the value of 0 to the variable “i”, named after the word “iteration”. This action is called “initializing”, in order to give an initial value to a variable.
  2. In the line after that, we’re starting the while loop. We’re setting a condition for this loop that “i” needs to be smaller than 5. Right now, “i” is 0 since it’s just been initialized, so this condition is currently true.
  3. On the next two lines, we have a block that’s indented to the right. Here, we can use the characteristic shared with Python functions, which indicates that every line of code that shares the same amount of indented spaces will be part of the body of the function, or loop in this case.
  4. There are two lines in the body of the loop. In the first line, we print a message followed by the current iteration, represented by the value of “i”. In the second line, the value of “i” is incremented. We do this by adding 1 to its current value and assigning it back to “i”. So after the first execution of the body of the loop, “i” will be 1 instead of 0.

Because this is a loop, the computer doesn’t just continue executing with the next line in the script. Instead, it loops back around to re-evaluate the condition for the while loop.

And because 1 here is still smaller than 5, it executes the body of the loop again. The computer will keep doing this until the condition isn’t true anymore. In this example, the condition will be false when “i” is no longer smaller than 5. Once the condition is False, the loop finishes, and the next line of the code is executed.

Avoiding the Infinite Loop trap

As previously told, while loops use the condition to check whether to exit from the loop structure. The body of the while loop needs to make sure that the condition being checked will change. If it doesn’t change, the loop may never finish and we get what’s called an infinite loop, a loop that keeps executing and never stops.

Take the following code as an example. As in the previous case, we initialized the “i” variable, but forgot to add an index inside the loop to refresh the variable in each iteration. As a consequence, the loop will run until we manually interrupt it with the CTRL+C commands:

Image for post
Image for post

In order to avoid this issue, it’s a good idea to take a moment to consider the different values a variable can take. This helps you make sure the loop won’t get stuck during the iteration.

Should you always try to avoid infinite loops?

While you need to watch out for infinite loops, they are not always a bad thing.

Sometimes you actually want your program to execute continuously until some external condition is met.

If you’ve used the ping utility on Linux or macOS system, or ping-t on a Windows system, you’ve seen an infinite loop in action. This tool will keep sending packets and printing the results to the terminal unless you send it the interrupt signal, usually pressing Ctrl+C.

In Python, we usually create our loops with an automatic indication to interrupt the iteration with the keyword break, which you can see in the code below, to signal that the current loop should stop running:

Image for post
Image for post

As you can see, the indicated procedure was to add 1 to the variable “i” for each iteration, until it reaches a value of 10, when it should interrupt the process. The logic of the code would be something like this:

Image for post
Image for post

2. For Loops

A for loop iterates over a sequence of values. A very simple example of a for loop is to iterate over a sequence of numbers, for example from 0 to 4.

Image for post
Image for post

Notice that the structure is kind of similar to the structures of while loops. The first line indicates the distinguishing for keyword and it ends with a colon. The body of the loop is indented to the right, like in the while loop, the if block, and the function definitions. What’s different in this case is that we have the keyword in.

Also, between the for keyword and in keyword, we have the name of a variable, in this case “i” for “index”. This variable will take each of the values in the sequence that the loop iterates through. So in this example, it’ll iterate through a sequence of numbers generated using the range() function.

As a reminder, in Python and a lot of other programming languages, a range of numbers will start with the value 0 by default. In addition, the list of numbers generated will be one less than the given value. In the simple example here, “i” will take the values 0, 1, 2, 3, and 4.

At this point in the article you might be wondering: Why have two loops that look like they do the same thing?

Well, the power of the for loop is that we can use it to iterate over a sequence of values of any type, not just a range of numbers. For example, we can iterate over a list of string or words:

Image for post
Image for post

The sequence that the for loop iterates over could contain any type of element, not just strings. For example, we could iterate over a list of numbers to calculate the total sum and average.

Image for post
Image for post

In this example, we’re defining a list of values. After that, we’re initializing two variables, some and length, that will update in the body of the for loop. In the for loop, we’re iterating over each of the values in the list, adding the current value to the sum of values, and then also adding 1 to length, which calculates how many elements there are in the list. Once we’ve gone through the whole list, we print out the sum and the average.

We’ll keep using for loops in our examples every time we want to iterate over the elements of any sequence and operate with them.

How do you identify which loop to use?

If you’re wondering when you should use for loops and when you should use while loops, there’s a way to tell:

  • Use for loops when there’s a sequence of elements that you want to iterate.
  • Use while loops when you want to repeat an action until a condition changes.

And if whatever you’re trying to do can be done with either for or while loops, just use whichever one’s your favorite.

Level up your looping skills: Nested Loops

Basically, a Nested Loop is a one or more for loops inside another loop. For example, suppose that you have to prepare the schedule for a tennis tournament with four of our favorite players that will play against each other.

To prepare our schedule, let’s sort the players with a Python script that will output all possible match pairings. For this, the order of the names matters because for each game, the first name will be the one player and the second name will be the contender. Of course, what we don’t want to do is have a player against itself. To do this, we need to use a conditional that makes sure we only print the pairing when the names are different.

Image for post
Image for post

As you can see, Nested Loops are very useful for solving certain problems, such as sorting players in a tournament.

Common Mistakes with Loops

  1. Iterating over non-sequences: As I’ve mentioned already, for loops iterate over sequences. Consequently, Python’s interpreter will refuse to iterate over single elements, such as integers or non-iterable objects.
  2. Failure to initialize variables. Make sure all the variables used in the loop’s condition are initialized before the loop.
  3. Unintended infinite loops. Make sure that the body of the loop modifies the variables used in the condition, so that the loop will eventually end for all possible values of the variables.
  4. Forgetting that the upper limit of a range() isn’t included.

As a practical example of the first scenario, let’s try to iterate an integer:

Image for post
Image for post

There are two solutions to this problem, depending on what we’re trying to do:

  • If you want to go from zero to 25, then we use the range function.
  • If you’re trying to iterate over a list that has 25 as the only element, then it needs to be a list.

3. Recursion

Recursion is the third mechanism in Python to loop through a sequence of values in addition to while and for loops.

While Recursion is a very common technique used in software engineering, it’s not much used in automation tasks. Still, it’s valuable to know about it as you might encounter it in someone else’s code or, even more importantly, you might face a problem where recursion is the best way to solve it.

Recursion is the repeated application of the same procedure to a smaller problem.

A great visual example for these methods are Russian nesting dolls:

Image for post
Image for post
Photo by cottonbro from Pexels

As you might see, each doll has a smaller doll inside it. When you open up the doll to find the smaller one inside, you keep going until you reach the smallest doll which can't be opened. Recursion lets us tackle complex problems by reducing the problem to a simpler one.

Imagine that we want to find how many dolls there are in total, we would need to loop over each doll until we get to the last one and then count how many dolls we’ve opened. That’s recursion in action.

In programming, recursion is a way of doing a repetitive task by having a function call itself. A recursive function calls itself usually with a modified parameter until it reaches a specific condition. This condition is called the base case.

In the Russian dolls example, the smallest doll would be the base case. Let’s try a real-life problem, in which we’ll try to code a function that calculates the factorial of a number. In mathematics, the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n:

Image for post
Image for post

As you can see in the code above, the function factorial() calls itself in order to solve factorials for numbers greater than 1. Each time the function is executed, it calls itself with a smaller number until it reaches the base case. Once it reaches the base case, it returns the value 1. This loop will keep going until the first factorial() function returns the desired result.

You might be wondering why do we need recursive functions if I can just use a for or while loop?

Because solutions to some specific problems are easier to write and understand when using recursive functions. For example, for IT specialists trying to automate tasks, recursion would be a useful tool to inspect a computer’s directory as each directory will contain sub-directories which contain files.

The base case would be a directory with no sub-directories. For this case, the function would just return the amount of files, but for the remaining sub-directories it would call the recursive function. When operating with recursive structures, it’s often easier to use recursive functions instead of for or while loops.

It’s important to call out that in some languages there’s a maximum amount of recursive calls you can use. In Python by default, you can call a recursive function 1,000 times until you reach the limit. That’s fine for things like sub-directories or similar recursive structures.

Conclusion

In this article I explained how to tell a computer to do an action repetitively. Python gives us three different ways to perform repetitive tasks: while loops, for loops, and recursion.

For loops are best when you want to iterate over a known sequence of elements but when you want to operate while a certain condition is true, while loops are the best choice.

If you liked the information included in this article don’t hesitate to contact me to share your thoughts. It motivates me to keep on sharing!

Related articles for further insights to Python Programming:

Creating stock’s price simulator:

Learn how to code amazing visualizations in Python:

Data Analysis of New York with Python:

Thanks for taking the time to read my article! If you have any questions or ideas to share, please feel free to contact me to my email, or you can find me in the following social networks for more related content:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK