Assume you need to print all integers from 1 to 99. Without a loop this takes 99 print statements:
print(1) print(2) . . print(99)
If tomorrow we want print the numbers from 1 to 200, we would need to add 101 print statements to the code!
A loop – in this case a for-loop – gives us an abstraction leading to flexibility. We need to change only one number to vary the number of integers printed:
for number in range(1,100): print(number)
# 02Loops example_01 WhyLoops.py last_number = 99 for number in range(1,last_number+1): print(number)
The range function is the most commonly used construct in for-loops. The following video gives a brief review/refresher on the various ways we can use range to generate a sequence of integers to iterate over. Video Length: 4:18