range
of possiblities
start=0
and step=1
.10
that are smaller than 0
.step=-2
the order of the range is reversed, so it produces the list of numbers greater than stop
.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. In order to avoid using len
we also need to increment a counter:
pressures = [0.273, 0.275, 0.277, 0.275, 0.276]
sum_pressures = 0.0
num_pressures = 0
for pressure in pressures:
sum_pressures += pressure
num_pressures += 1
mean_pressure = sum_pressures / num_pressures
print("The mean pressure is:", mean_pressure)
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 value += new_value
. This is the same as writing value = value + new_value
but is shorter and easier to read.
string = "Hello world!"
for ch in string:
print(ch)
.