In Programming a Continuous or Repeated Action That You Want to Perform Over and Over Again Is
Repeating Actions with Loops
Overview
Teaching: 30 min
Exercises: 0 minQuestions
How can I do the same operations on many different values?
Objectives
Explain what a
for
loop does.Correctly write
for
loops to repeat simple calculations.Trace changes to a loop variable as the loop runs.
Trace changes to other variables as they are updated by a
for
loop.
In the episode virtually visualizing information, we wrote Python code that plots values of interest from our first inflammation dataset (inflammation-01.csv
), which revealed some suspicious features in it.
Nosotros have a dozen data sets correct at present and potentially more on the fashion if Dr. Bohemian can continue upwards their surprisingly fast clinical trial rate. We desire to create plots for all of our data sets with a single statement. To do that, we'll have to teach the computer how to echo things.
An example job that we might desire to repeat is accessing numbers in a list, which nosotros will do past press each number on a line of its own.
In Python, a listing is basically an ordered collection of elements, and every element has a unique number associated with information technology — its index. This ways that we can access elements in a list using their indices. For example, we can get the commencement number in the list odds
, by using odds[0]
. Ane fashion to print each number is to utilise four print
statements:
print ( odds [ 0 ]) impress ( odds [ i ]) print ( odds [ 2 ]) print ( odds [ 3 ])
This is a bad approach for iii reasons:
-
Non scalable. Imagine you need to print a listing that has hundreds of elements. It might be easier to type them in manually.
-
Difficult to maintain. If we want to decorate each printed element with an asterisk or any other character, we would take to modify 4 lines of code. While this might not be a problem for small lists, it would definitely be a problem for longer ones.
-
Fragile. If we utilise it with a list that has more than elements than what nosotros initially envisioned, it will just display function of the listing'due south elements. A shorter listing, on the other manus, volition cause an error because it will be trying to brandish elements of the listing that do not exist.
odds = [ 1 , 3 , 5 ] print ( odds [ 0 ]) print ( odds [ 1 ]) impress ( odds [ 2 ]) print ( odds [ 3 ])
--------------------------------------------------------------------------- IndexError Traceback (most contempo call last) <ipython-input-three-7974b6cdaf14> in <module>() iii print(odds[i]) 4 print(odds[2]) ----> five print(odds[three]) IndexError: list index out of range
Hither's a better approach: a for loop
odds = [ ane , 3 , 5 , seven ] for num in odds : print ( num )
This is shorter — certainly shorter than something that prints every number in a hundred-number list — and more robust likewise:
odds = [ 1 , 3 , 5 , 7 , 9 , 11 ] for num in odds : print ( num )
The improved version uses a for loop to repeat an operation — in this case, printing — in one case for each affair in a sequence. The full general course of a loop is:
for variable in collection : # do things using variable, such every bit print
Using the odds instance above, the loop might look like this:
where each number (num
) in the variable odds
is looped through and printed one number after another. The other numbers in the diagram announce which loop cycle the number was printed in (ane being the offset loop cycle, and 6 being the last loop bicycle).
We can call the loop variable anything nosotros like, simply at that place must be a colon at the terminate of the line starting the loop, and we must indent anything we want to run inside the loop. Different many other languages, there is no command to signify the end of the loop body (eastward.g. end for
); what is indented after the for
statement belongs to the loop.
What's in a proper noun?
In the case in a higher place, the loop variable was given the name
num
as a mnemonic; it is short for 'number'. We can cull any proper noun we want for variables. We might just equally easily have chosen the namebanana
for the loop variable, equally long every bit we employ the same name when we invoke the variable inside the loop:odds = [ 1 , 3 , five , 7 , ix , eleven ] for banana in odds : print ( banana )
It is a good idea to cull variable names that are meaningful, otherwise it would be more hard to sympathize what the loop is doing.
Hither'south another loop that repeatedly updates a variable:
length = 0 names = [ 'Curie' , 'Darwin' , 'Turing' ] for value in names : length = length + 1 impress ( 'There are' , length , 'names in the list.' )
There are 3 names in the list.
It's worth tracing the execution of this little plan footstep by footstep. Since at that place are three names in names
, the statement on line four will exist executed three times. The commencement time around, length
is zero (the value assigned to it on line i) and value
is Curie
. The statement adds ane to the sometime value of length
, producing 1, and updates length
to refer to that new value. The next time effectually, value
is Darwin
and length
is 1, so length
is updated to be two. After one more than update, length
is three; since there is nothing left in names
for Python to procedure, the loop finishes and the print
function on line v tells us our final answer.
Annotation that a loop variable is a variable that is being used to tape progress in a loop. It still exists after the loop is over, and we can re-utilise variables previously divers as loop variables also:
proper name = 'Rosalind' for name in [ 'Curie' , 'Darwin' , 'Turing' ]: impress ( proper name ) impress ( 'after the loop, name is' , proper noun )
Curie Darwin Turing afterwards the loop, name is Turing
Notation besides that finding the length of an object is such a common operation that Python really has a born function to do it called len
:
len
is much faster than whatever function we could write ourselves, and much easier to read than a two-line loop; it volition also give us the length of many other things that we haven't met yet, so we should always use it when we tin can.
From 1 to Due north
Python has a built-in function called
range
that generates a sequence of numbers.range
tin can accept 1, ii, or 3 parameters.
- If 1 parameter is given,
range
generates a sequence of that length, starting at zero and incrementing by 1. For example,range(3)
produces the numbers0, 1, 2
.- If ii parameters are given,
range
starts at the first and ends just before the second, incrementing by 1. For example,range(ii, 5)
produces2, 3, 4
.- If
range
is given 3 parameters, it starts at the first ane, ends merely earlier the second one, and increments past the third one. For example,range(three, 10, ii)
produces3, 5, 7, 9
.Using
range
, write a loop that usesrange
to print the commencement three natural numbers:Solution
for number in range ( 1 , 4 ): impress ( number )
Understanding the loops
Given the following loop:
give-and-take = 'oxygen' for char in word : impress ( char )
How many times is the trunk of the loop executed?
- 3 times
- iv times
- v times
- 6 times
Solution
The body of the loop is executed 6 times.
Calculating Powers With Loops
Exponentiation is built into Python:
Write a loop that calculates the aforementioned upshot as
5 ** iii
using multiplication (and without exponentiation).Solution
result = one for number in range ( 0 , 3 ): upshot = result * 5 print ( event )
Summing a list
Write a loop that calculates the sum of elements in a list by adding each element and printing the final value, then
[124, 402, 36]
prints 562Solution
numbers = [ 124 , 402 , 36 ] summed = 0 for num in numbers : summed = summed + num print ( summed )
Computing the Value of a Polynomial
The built-in function
enumerate
takes a sequence (e.g. a listing) and generates a new sequence of the aforementioned length. Each element of the new sequence is a pair composed of the index (0, 1, 2,…) and the value from the original sequence:for idx , val in enumerate ( a_list ): # Practice something using idx and val
The code above loops through
a_list
, assigning the alphabetize toidx
and the value toval
.Suppose y'all have encoded a polynomial as a list of coefficients in the following way: the kickoff chemical element is the constant term, the 2d chemical element is the coefficient of the linear term, the third is the coefficient of the quadratic term, etc.
10 = 5 coefs = [ 2 , four , 3 ] y = coefs [ 0 ] * ten ** 0 + coefs [ i ] * x ** 1 + coefs [ 2 ] * x ** 2 impress ( y )
Write a loop using
enumerate(coefs)
which computes the valuey
of whatsoever polynomial, givenx
andcoefs
.Solution
y = 0 for idx , coef in enumerate ( coefs ): y = y + coef * x ** idx
Key Points
Use
for variable in sequence
to process the elements of a sequence one at a time.The torso of a
for
loop must be indented.Use
len(thing)
to determine the length of something that contains other values.
Source: https://swcarpentry.github.io/python-novice-inflammation/05-loop/
0 Response to "In Programming a Continuous or Repeated Action That You Want to Perform Over and Over Again Is"
Post a Comment