range
of possiblities
print(list( range(0, 10, 1) ))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
This does exactly what our first range command did, we have just explicitly specified the default values, start=0
and step=1
.
print(list( range(0, 10, 2) ))
[0, 2, 4, 6, 8]
This steps through the even integers, because we have changed the value of step
from the default 1 to 2.
print(list( range(10, 0) ))
[]
This returns an empty list because there are no numbers starting at 10
that are smaller than 0
.
print(list( range(10, 0, -2) ))
[10, 8, 6, 4, 2]
Because of step=-2
, the order of the range is reversed and so it produces the list of numbers greater than stop
.
print(list( range(1, 2, 0.1) ))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-16-1be1b2d16426> in <module> ----> 1 print(list( range(1, 2, 0.1) )) TypeError: 'float' object cannot be interpreted as an integer
range
takes only integer values so this raises a TypeError: 'float' object cannot be interpreted as an integer
.
In the first example of a loop we assigned a list to numbers and used this as the collection of values to loop over - we can do exactly the same here.
We can avoid using len
by looping over the values in pressures
, but we still need a variable num_pressures
to count the number of pressures we summed up, and sum_pressures
to record the running total:
pressures = [0.273, 0.275, 0.277, 0.275, 0.276]
sum_pressures = 0.0
num_pressures = 0
for p in pressures: #for each value p in the list pressures
sum_pressures += p #add the value of p to the current total
num_pressures += 1 #add one to the number of values we have added up
mean_pressure = sum_pressures / num_pressures
print("The mean pressure is:", mean_pressure)
The mean pressure is: 0.2752
Generally this would be considered more "pythonic" than the previous example, because it is more readable.
'For each index in a range the length of the list pressures ...' is not as readable as 'For each pressure in the list of pressures ...'.
We have also introduced the accumulator operator +=
in the line
value += new_value
This is the same as writing value = value + new_value
but is shorter and easier to read.
There is also a "deccumulator" (that's not an official name) operator -=
which does what you expect;
value -= new_value
is the same as
value = value - new_value
We can use the same idea as before, remember to read Python's for
loop syntax as
for item in my_list:
for character in "Hello world!":
print(character)
H e l l o w o r l d !