for ¶
A fundamental concept in programming, the
for
loop allows us to efficiently execute a set of commands a certain number of times.
Let's see how this works and then I'll explain it.
for i in range(5):
print(i)
print("Done!")
0 1 2 3 4 Done!
Okay, so we have a few new things here.
First, we have our standard
:
and then indent syntax; which makes sense because we need to tell Python what to repeat.
We have seen the
range(5)
before, but
for i in
looks different.
What happens if I just take out
i in
.
for range(5)
print(
Wait, what do I put inside the print statement?
I need a variable to put inside
print()
, and that is exactly what the
i in
part does.
for
will ask
range(5)
for a value, and then store it
in
i
.
I can then use
i
inside of my
for
loop.
However,
for range(5) in i
does not read well, so we change its order to
for i in range(5)
to make it flow better.
Okay, do I have to use a generator in a
for
loop?
Nope!
You can use anything that
for
can ask for one value at a time, like in a list.
colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
for color in colors:
print(color)
red orange yellow green blue indigo violet
Remember, the
for
loop is asking the list for a value, storing it in a variable, and repeat.
I do not necessarily have to name the variable
color
.
for onomatopoeia in colors:
print(onomatopoeia)
red orange yellow green blue indigo violet
I also do not technically use the
for
loop variable as well.
for color in colors:
print("Hellllloooooooo")
Hellllloooooooo Hellllloooooooo Hellllloooooooo Hellllloooooooo Hellllloooooooo Hellllloooooooo Hellllloooooooo
Another common usage of
for
loop is to builds lists.
For example, suppose you have a bunch of temperatures in Celsius that you want to convert to Fahrenheit.
celsius_temps = [0, 10, 20, 30, 40]
We can use the formula to do just that.
$$ F = \frac{9}{5} C + 32 $$
def celsius_to_fahrenheit(temp):
return (9 / 5) * temp + 32
One valid—but tedious—way to do it is this.
fahrenheit_temps = []
fahrenheit_temps.append(celsius_to_fahrenheit(celsius_temps[0]))
fahrenheit_temps.append(celsius_to_fahrenheit(celsius_temps[1]))
fahrenheit_temps.append(celsius_to_fahrenheit(celsius_temps[2]))
fahrenheit_temps.append(celsius_to_fahrenheit(celsius_temps[3]))
fahrenheit_temps.append(celsius_to_fahrenheit(celsius_temps[4]))
print(fahrenheit_temps)
[32.0, 50.0, 68.0, 86.0, 104.0]
That's annoying.
Instead, I can use a
for
loop!
fahrenheit_temps = []
for temp in celsius_temps:
fahrenheit_temps.append(celsius_to_fahrenheit(temp))
print(fahrenheit_temps)
[32.0, 50.0, 68.0, 86.0, 104.0]
This framework is an extremely useful to to process or convert data.