Welcome to Loops and Iteration. Basically, this is where computers do repetitive tasks that we humans don't want to do. This is where the real power and the real benefit of computers happen.A loop is a sequence of operations that are performed over and over in some specified order. Loops can help you to eliminate repetition in code by replacing duplicate lines of code with an iteration, meaning that you can iteratively execute the same code line or block until it reaches a specified end point.
A loop is a used for iterating over a set of statements repeatedly.
Instead of copying and pasting the same code over and over to run it multiple times (say, on multiple variables or files), you can create a loop that contains one instance of the code and that executes that code block on a range or list of values that you provide.
For example, the following lines could be replaced by a loop that iterates over a list of variable names and executes the print() function until it reaches the end of the list:
print(avg_monthly_precip)
print(months)
print(precip_2002_2013)You can also provide a numerical range of values to control how many times the code is executed. In Python we have three types of loopsfor,whileanddo-while
for (variable) in (sequence): # body_of_loop that has set of statements # which requires repeated execution
Here (variable) is a variable that is used for iterating over a (sequence). On every iteration it takes the next value from (sequence) until the end of sequence is reached.
The following example shows the use of for loop to iterate over a list of numbers. In the body of for loop we are calculating the square of each number present in list and displaying the same.
In the above example, we have iterated over a list using for loop. However we can also use a range() function in for loop to iterate over numbers defined by range().
range(n):generates a set of whole numbers starting from 0 to (n-1).
For example:
range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]
range(start, stop):generates a set of whole numbers starting from start to stop-1.
For example:
range(5, 9) is equivalent to [5, 6, 7, 8]
range(start, stop, step_size): The default step_size is 1 which is why when we didn’t specify the step_size, the numbers generated are having difference of 1. However by specifying step_size we can generate numbers having the difference of step_size.
For example:
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]
Lets use therange()function in for loop:
Here we are usingrange()function to calculate and display the sum of first 5 natural numbers.
In Python we can have an optional ‘else’ block associated with the loop. The ‘else’ block executes only when the loop has completed all the iterations. Lets take an example:
Note:The else block only executes when the loop is finished.
When a for loop is present inside another for loop then it is called a nested for loop. Lets take an example of nested for loop.
In the example below, a list called files is defined with two text strings that represent two filenames. The for loop will run iteratively on each text string (represented by the placeholder fname in each iteration).
In the first iteration of the loop, fname is equal to the text string "months.txt"; in the second iteration, fname represents the text string "avg-monthly-precip.txt".
Note that print() returns the text string that is the filename, but not the values in the file.
This is because the list only contains text strings for the filenames, but does not actually contain the contents of the file. In fact, Python does not know that these text strings are filenames; it simply treats these as text string items in a list.
Taking another look at the definition of the list, you can notice that the items are just text strings identified by quotes "". The list does not contain variables or objects that have been defined (e.g. numpy arrays, pandas dataframes, or even other lists).
Thus, it is important to remember that the objects that you use in the loop will determine what output you will receive.
For example, you can define a list that contains multiple objects (say, other lists).
In the example below, theprint()returns the actual values in each item in the list because the items are defined objects (in this example, each item is its own list of data values).
In each iteration of the loop,dlistrepresents the data lists that you defined: in first iteration,months, andavg_monthly_precipin the second iteration.