Looping
Code sample link: https://replit.com/@jjoco/python-looping
Looping in Python is used to execute a given set of code repeatedly. There are two ways to loop in Python: for
loops and while
loops.
For loop
The for
keyword is used to iterate over an sequence or some iterable type.
The general syntax for simple for
loops is the following:
1 2 |
|
for
loop iterates through the iterable, the value at a given point in the iterable is written into elem
(which you can name to whatever you want, by the way). On each iteration, you'll be able to process each element in the iterable.
Let's go through several examples.
Iterate through string
We can process each character in a given string:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Iterate through list
Think of lists as an ordered sequence of values, like 1, 5, 6, 7
in that order. We'll go over lists in-depth in the Lists
section under the Collections
header.
We can iterate through each value in the list like the following:
1 2 3 |
|
Iterate through a range of ints
In other languages, to iterate through lists or arrays, the most common way is to use array indices to access array values. The key is to use Python's in-built range()
function, which returns a sequence of integers for 0
to n-1
if you use the range(n)
signature:
1 2 |
|
range(start, stop)
, in which a sequence of numbers from start
to stop-1
is returned. If you want to include the step, as well, use range(start, stop, step)
, which returns a sequence of numbers from start
to stop-1
in steps of step
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
So, to iterate through all elements in a list via indices, you'll have to input the length of the list as the argument in the range(n)
function:
1 2 3 |
|
While loop
One can use while
loops to execute code repeatedly. The syntax is follows:
1 2 |
|
So, let's say we have a counter that continues incrementing from 0
until 5
. We can write:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
5
, at which the program exits the while loop.
For those wondering, you can write the same for
loop as a while
or vice-versa. Generally, I use for-loops when iterating through something or the number of iterations can be known ahead of time; on the other hand, I use while-loops when my looping is dependent on some condition or the number of iterations is variable. For example, you shouldn't use a for-loop to write an infinite loop.
Infinite loop
The easiest way to write an infinite loop is via a while loop:
1 2 |
|
break
statement to exit the loop. You can use break
in either a for-loop or a while-loop to exit the current loop block.
1 2 3 4 5 6 |
|
-1
.