Repeated Iterations (Loops)

Repeating Code

numbers = [2, 3, 5]


squared = list()

squared.append(numbers[0] ** 2)
squared.append(numbers[1] ** 2)
squared.append(numbers[2] ** 2)
squared
[4, 9, 25]
squared = list()

squared.append(numbers[0] ** 2)
squared.append(numbers[1] ** 2)
squared.append(numbers[2] ** 2)
squared
[4, 9, 25]


This kind of coding exhibits bad programming practices such as :

  • Difficult to scale

  • Difficult to modify

  • Clarity

Don’t Repeat Yourself (DRY Principle)

The DRY in the DRY principle stands for “Don’t Repeat Yourself”. It is the principle of avoiding redundancy within code.

squared = list()

squared.append(numbers[0] ** 2)
squared.append(numbers[1] ** 2)
squared.append(numbers[2] ** 2)
squared
[4, 9, 25]

Loops

numbers = [2, 3, 5]


squared = list()

squared.append(numbers[0] ** 2)
squared.append(numbers[1] ** 2)
squared.append(numbers[2] ** 2)
squared
[4, 9, 25]


squared = list()
for number in numbers: 
    squared.append(number ** 2)
squared
[4, 9, 25]

For (Each) Loop

squared = list()
for number in numbers: 
    squared.append(number ** 2)
squared
[4, 9, 25]
404 image
squared = list()
numbers = [ 2, 3, 5]

for number in numbers: 
    squared.append(number ** 2)

squared
[4, 9, 25]


squared = list()
numbers = [ 2, 3, 5]

for thingamajig in numbers: 
    squared.append(thingamajig ** 2)

squared
[4, 9, 25]
squared = list()

for number in numbers: 
    squared.append(number ** 2)

squared
[4, 9, 25]
404 image
404 image
404 image
404 image

Let’s apply what we learned!