For loops¶
A for loop executes commands once for each value in a collection.¶
Doing calculations on the values in a list one by one is as painful as working with
pressure_001,pressure_002, etc.A for loop tells Python to execute some statements once for each value in a list, a character string, or some other collection.
“for each thing in this group, do these operations”
for number in [2, 3, 5]:
print(number)
This
forloop is equivalent to:
print(2)
print(3)
print(5)
And the
forloop’s output is:
A for loop is made up of a collection, a loop variable, and a body.¶
for number in [2, 3, 5]:
print(number)
A for loop is made up of a collection, a loop variable, and a body.¶
The collection,
[2, 3, 5], is what the loop is being run on.The body,
print(number), specifies what to do for each value in the collection.The loop variable,
number, is what changes for each iteration of the loop.The “current thing”.
The first line of the for loop must end with a colon, and the body must be indented.¶
The colon at the end of the first line signals the start of a block of statements.
Python uses indentation rather than
{}orbegin/endto show nesting.Any consistent indentation is legal, but almost everyone uses four spaces.
for number in [2, 3, 5]:
print(number)
Indentation is always meaningful in Python.
firstName = "Jon"
lastName = "Smith"
This error can be fixed by removing the extra spaces at the beginning of the second line.
Loop variables can be called anything.¶
As with all variables, loop variables are:
Created on demand.
Meaningless: their names can be anything at all.
for anything in range(5):
print(anything)