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?
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.
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.
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:
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.
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()
.
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.
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:
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
:
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
The For Loop Implementation
Infinite Looping
An infinite loop, as you have been shown already, is a loop which never ends.
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
Was this helpful?