Before we get to writing our own loops, let’s explore what programming would be like if we couldn’t use loops.
Let’s say we have a list of
ingredients and we want to print every element in the list:
ingredients = ["milk", "sugar", "vanilla extract", "dough", "chocolate"]
If we only use
print(), our program might look like this:
print(ingredients) print(ingredients) print(ingredients) print(ingredients) print(ingredients)
The output would be:
milk sugar vanilla extract dough chocolate
That’s still manageable, We’re writing 5
print() statements (or copying and pasting a few times). Now imagine if we come back to this program and our list had 10, or 24601, or … 100,000,000 elements? It would take an extremely long time and by the end, we could still end up with inconsistencies and mistakes.
Don’t dwell too long on this tedious scenario — we’ll learn how loops can help us out in the next exercise. For now, let’s gain an appreciation for loops.
print() statements, print out:
"This can be so much easier with loops!".