The computer exists to make human work easier. It never gets bored, so it can run the same command over and over without needing a rest.
Doing something repeatedly like this is called repetition or looping. Looping is also one of the control structures in a programming language.
Python has 2 kinds of loop: the for loop and the while loop. How do you use them? This time you'll look at the for loop first.
FOR Loop, Iteration, and Iterable
The for loop is a loop where you already know when it starts and when it ends. In other languages like Pascal, Java, and C++, a for loop runs with a counter. Python is a little different, because you use something called an iterable.
A loop that uses an iterable as its data subject is often called iteration.
An iterable is a collection of data gathered into one, and you can reach it in order from its head to its tail. Almost every data type that holds many values is iterable. Two you have already covered are string (holds many characters) and list (holds many free values).
This time you'll use another iterable, namely range. A range holds many consecutive whole numbers (integers). To create one, you can use the range() function with 1 to 3 arguments.
range(<nilai_akhir>)
range(<nilai_awal>, <nilai_akhir>) # or
range(<nilai_awal>, <nilai_akhir>, <step>) # or
Take a look at the examples:
range(10)= 0, 1, 2, 3, 4, 5, 6, 7, 8, 9range(5, 10)= 5, 6, 7, 8, 9range(1, 10, 2)= 1, 3, 5, 7, 9range(5, 0, -1)= 5, 4, 3, 2, 1
From those examples the role of each argument should be clear. Now back to the first question: how do you use range inside a for loop?
Structure of the FOR Loop in Python
In general, the structure of a for loop in Python looks like this:
for <variable> in <iterable>:
<perintah>
<variable>: holds the iterable element on each iteration<iterable>: the value that becomes the subject of the iteration / loop<perintah>: one or several commands that will run
Using the FOR Loop
Now let's try a case. How would you print the text "Hello world" 5 times?
A first alternative might be to just call print("Hello World") 5 times, like this:
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
That way isn't wrong, but as a programmer, writing the same thing over and over feels off. It gets worse when a case forces you to run the same command 100 times, or even 1,000,000 times. Imagine copy-pasting all of that by hand 😥.
This is where a loop helps a lot. The five lines of Hello World code now fit into 2 lines.
for i in range(5):
print("Hello World")
Try running that code and see what happens.
Next, change the 5 in range(5) to a bigger number like 100 and watch what happens after you run it. Spoiler: the text "Hello World" appears as many times as the number inside range.
Is that all? Of course not. There is a lot you can do with this loop. A simple example is printing the numbers 1 through 10 in order.
for i in range(1, 11):
print(i)
Now run that code, and the output will look more or less like this:
1
2
3
4
5
6
7
8
9
10
How does that code work?
Right after the for keyword, you declare the variable i to store the value from range(1, 11), which holds the numbers 1 through 10. Then the iteration takes values from range(1, 11) and puts them into i one by one, from head to tail. On every pass, the command print(i) runs to print the value of the variable i. That command is called exactly 10 times.
Remember, the
rangefunction in Python is exclusive. That means the values it produces start at the first value and stop at the last value minus 1.range(n)= 0, 1, ..., n-1range(n, m)= n, n+1, n+2, ..., m-1
Even More Uses for the FOR Loop
Earlier you printed consecutive numbers from 1 to 10. This time you'll try printing a number series with a gap of 2, from 1 to 10. How would you do it?
For this you need to fill the 3rd argument of the range function. That argument is named step, and it works as an extra increment. When you leave it out, its value is 1, which is why range always produces consecutive numbers.
Now modify the code you built earlier.
for i in range(1, 11, 2):
print(i)
Run it and look at the result. It will look more or less like this:
1
3
5
7
9
Because you start at 1 with a step of 2, what comes out is the series of odd numbers. If you change the range to range(0, 11, 2), what comes out is the even numbers from 0 to 10.
Now, what if you want to count down?
Easy. You only need a start value that is bigger than the end value, then put a negative number as the step. Like this:
for i in range(5, 0, -1):
print(i)
Then the output will look like this:
5
4
3
2
1
Using Other Iterators (string and list)
At the start I said the for loop in Python uses an iterator, and the iterator isn't only range. A string and a list work too.
To prove it, try running the code below.
kalimat = "Belajar Python di Invasikode"
kata_kata = ["Belajar", "Python", "di", "Invasikode"]
for huruf in kalimat:
print(huruf)
for kata in kata_kata:
print(kata)
Go ahead and run it, then see what happens.
Closing
By this point I hope you have the concept, hehe. That's all for now, and I hope it's useful. Next time you'll look at repetition using the WHILE loop in Python 3.
See ya 😉