Loops

Welcome back to the Python basics tutorial! Today you're gonna learn about loops.A loop is basically a block of code that is executed repeatedly.

If I told you to print "Hello World" 10 times, what would you do?

print('Hello World.')
print('Hello World.')
print('Hello World.')
print('Hello World.')
print('Hello World.')
# .... 5 more times

The code does look ugly and verbose, doesn't it? Wouldn't it be nicer to have a shorter solution? For this task, you have to use loops. There are two kinds of loops in Python, the While loop and the For loop.

The While Loop

A while loop runs a block of code until a specified condition is evaluated to be false.

num = 1
while num < 10:
    print(num)
    num = num + 1

The above code translates to: while num is smaller than 10, print num, and add one to num. So, we go through 1, 2, 3, 4 and all the way to 10, where we add 1 to make it 11, which causes num < 10 to evaluate to false. Let's try removing the num = num + 1 and see what happens.

num = 1
while num < 10:
    print(num)

Run the code. What's happening? Do you see countless ones being printed? That's because we're never changing the value of 1, so num < 10 is always True. A sample game loop:

running = True:
while running:
    choice = input('Do you want to go left or quit?')
    if choice == 'left':
        print('Going left...')
    elif choice == 'quit':
        running = False

Press CTRL+C in the Python prompt to stop the loop.

The For Loop

A For loop "iterates" or "moves" through an "iterable" object, such as a list or a tuple.

fruits = ['apple', 'orange', 'strawberry']
for fruit in fruits:
    print(fruit)

If you run this code, you should see each of the fruits being printed one after another. The code is really easy to understand. The loop takes the first element in fruits, assigns it to a temporary variable named fruit which can only be accessed inside the for loop's code block.

Then, it moves on to the next element, does the same stuff we put in the code block, and moves to the next, till the very end of the list.

You can use it to execute something 4 times too with range().

for i in range(4):
    print('I\'m loooooping!')

i is often a temporary variable used in for loops.

This will print "I'm loooooping!" 4 times. You can use the for loop along with range to print all the numbers between 1 to 100.

for i in range(1, 100): # This means 1 to 100.
    print(i)

And run! you should see all the numbers from 1 to 99 printed. Wait, 99???!!!

Yes, 99. Ranges are not inclusive in Python, which means we only count up to 100, not including it. To avoid this, just replace 100 with 101.

The 'break' statement

Sometimes, we may want to stop or "break out" of a loop. We do it like this:

for i in range(10):
    if i == 7:
        print('Uh oh, we\'re at seven!')
        break
    print(i)

This code prints all the numbers from 1 to 10 until 7, where it stops the loop and prints "Uh oh, we're at seven!".

The 'continue' statement

If we need to skip doing something on a specific iteration, we use continue:

for i in range(10):
    if i == 4:
        continue # We skip 4 coz it ain't cool
    print(i)

We go from 3 to 5 and skip 4.

Comparison of the Loops

Both loops can be used to achieve the same results. Let's try to print Hello World ten times with both kinds of loops.

The While Loop Implementation

counter = 0
while counter < 10:
    print('Hello World')
    counter += 1

The For Loop Implementation

for i in range(10):
    print('Hello World')

Infinite Looping

An infinite loop, as you have been shown already, is a loop which never ends.

while True:
    print('Yaaaaaaaayy!')

Conclusion

As you can see, both of them can be used to achieve the very same results. It boils down to preference at the end of the day. Hope I managed to explain loops properly!

Last updated