Looping in Python.

Nur Indah Pratiwi
2 min readApr 5, 2021

What is Looping ?

Looping is a statement or instruction given to the computer so that it wants to do something whether it is processing data, displaying data, or others repeatedly. By using loops, the time needed to create a program will be shorter. example :

print (1,2,3,4,5)#output
1 2 3 4 5

Looping “FOR”

Looping For is more used in loops that have a known number of loops (countable).

The variables in the For declaration above are used to hold temporary values ​​of the sequence or series data type. Such as strings, lists, tuples, and others. Switch to the line below, so that the code can be repeated later, then give space or space to indent to the right. Because the indentation rules apply here. This area can also be said to be the body of the For loop. Then if you want to get out of the body or the For code block, then align the next line of code with the previous For instruction.

example :

for i in range(10):
print("cow ke-{}".format(i))

Cow -0
Cow -1
Cow -2
Cow -3
Cow -4
Cow -5
Cow -6
Cow -7
Cow -8
Cow -9
print("the number of cows:", i)the number of cows : 9

The range function (10) is used to create a sequence with a length of 10, starting from the numbers 0 to 9. Then like the previous formula i which is a variable is used to hold the temporary value of the sequence generated from the range () function.

  • String in For

example :

website = "google.com"
for i in website:
... print(i)
...
g
o
o
g
l
e
.
c
o
m
  • List in For

example :

students = ["Kiki", "Lisa", "Cika", "Dani", "Eko"]
>>> for i in students:
... print(i)
...
Kiki
Lisa
Cika
Dani
Eko

Looping “While”

While is an uncountable loop with an unspecified number of repetitions. It will run the line of code inside the block of code continuously as long as it satisfies the predefined expression, which means it will repeat as long as the condition is True.

example :

number = 1
>>> while number < 10:
... print(number)
... number += 1 #add this code
1
2
3
4
5
6
7
8
9

Every time the loop process is completed, the value of the number variable will always increase by 1 until it meets the limit (10). When it reaches the limit, the while loop will stop because the value has become False.

Nested Loop

for line in range(5):
... for column in range(line+1):
... print('*', end='')
... print()
...
*
**
***
****
*****

--

--