Loops are a way to repeatedly execute some code. Here's an example:
In [1]:
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for planet **in** planets:
print(planet, end=' ') *# print all on same line*
Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune
The for
loop specifies.
planet
)planets
)You use the word "in
" to link them together.
The object to the right of the "in
" can be any object that supports iteration. Basically, if it can be thought of as a group of things, you can probably loop over it. In addition to lists, we can iterate over the elements of a tuple:
In [2]:
multiplicands = (2, 2, 2, 3, 3, 5)
product = 1
for mult **in** multiplicands:
product = product * multproduct
Out [2]: