In python we use loops to repeat a process while a certain condition is met or to perform an action on elements in an object such as a list. There are two types of loops in Python; While Loops and For Loops.
While loops enable us to set a conditional statement upon which the loop keeps running and the action we define keeps on happening. We write conditional statements in a similar way as we do for if statements but instead of performing a single action, Python keeps performing the action until the statement evaluates to False.
Imagine you are pumping up a tyre. Until the tyre is full inflated you will keep performing the action of pumping the tyre then checking how much it is inflated and if it is not fully inflated repeating the action. We can think of a while loop in this way, where the conditional statement would be “While the tyre is not fully inflated” and the action would be to pump the tyre. Once the tyre is inflated then the statement evaluates to false and we stop pumping (the loop ends).
Let’s see how to implement this in Python.
For loops allow us to perform actions or processes on a pre-defined set of elements such as a range of numbers, list, dictionary or any other object in Python. This allows us to write an algorithm that does something to a collection of elements without having to write the code to explicitly perform the action on each individual element. Let’s try this now.
If we wanted to square all the numbers in a list without a For loop we would have to code the operation for each element individually like below.
If we use a For loop however, we only have to code the operation once, no matter how many elements are involved.
Not only can we perform operations on existing elements, we can also use For loops to generate new elements based on some logic we define. Let’s try this by appending another 4 values to our numbers list based on the pattern of numbers that already exist.
Now that we have explained loops you might be wondering how these might be useful in a Data science context. You will generally find For Loops more useful when working with data in Python than While Loops as we will often be working with pre-defined data structures. We will use for loops to iterate over these data structures when we want to modify the data in the same way such as multiplying the values by changing the data types of some fields. We will see more specific examples when we move onto actually doing some data science with Python.
Generate a list called new_list and append the numbers 0, 10, 20, 30 and 40 using a For loop.