Loops

Loops are a way of repeating certain lines of codes several times. Without loops we would need to repeat the lines over and over which is not very efficient.

Example - no loops

If we want to print the test “Happy Birthday” seven times, then without loops it would look like:

print("Happy Birthday")
print("Happy Birthday")
print("Happy Birthday")
print("Happy Birthday")
print("Happy Birthday")
print("Happy Birthday")
print("Happy Birthday")

This is inefficient because if we want to change the message then we need to change it seven times and if we wanted to print the message 700 times then we would need the same line 700 times.

Example - loops

The more efficient way to do this is to use a loop. The for loop will repeat lines of code a set number of times.

for counter in range(7):
	print("Happy Birthday")

This loop will still display the text “Happy Birthday” seven times, but it only takes two lines of code. If we wanted to print it 700 times then it would still only take two lines of code.

Fixed Loops

THe for loop above is called a fixed loop. It is called this because it will always repeat the exact number of times specified.