Learn About Loop in Python

Ahmad Adli
5 min readDec 24, 2021

--

Loops in programming are lines of code that are executed by the computer repeatedly until certain conditions are met. This loop can be used by all programming languages, including Python.

In Python, there are two types of loops. That is:

  1. While
  2. For

While can be used for loops where the number of iterations is known and the number of iterations is unknown. In the use of While, only the conditions of the loop are known.

And the use of For can only be used for loops that have a predetermined number of repetitions.

First, we’ll learn how to use the While loop.

While Loop

Syntax of While loop:

while condition:      program ...      program ...

As long as the condition is True, the program in the While loop will continue to run. And will stop only if the condition is False.

Example:

n = 1while n <= 5:      print("Hello World")      n = n + 1

Output:

Hello World
Hello World
Hello World
Hello World
Hello World

In the above program, we make the value n = 1, if we make it 0, then the output will repeat 6 times. Because python uses an integer system that counts numbers starting from 0.

And the condition for the program is n ≤ 3, which means that as long as the value of n has not reached 3, it will continue to run. And n + 1 is used to add 1 value to n. So that the value of n which was previously 1 will continue to increase by 1 as long as the program is run.

In the while loop, you can use the ‘True’ condition, which means the program will continue to run without stopping. Look at the following example.

Script:

while True:      password = input("Input Password: ")

Output:

Input Password: 123
Input Password: 142
Input Password: 1531
Input Password: 102
Input Password: 1542
Input Password:
...

The program will run without stopping because in the program there is no command to stop the program. The stop command to stop the While looping program with the condition True is to use ‘break’.

while True:      password = int(input("Input Password: "))      if password == 4321:         break
print("Hello, there!")

Output:

Input Password: 2532
Input Password: 1234
Input Password: 4321
Hello, there!

In the loop, we can add a continue statement, which is to skip the current iteration to the next iteration. Look at the following example.

Script:

i = 1while i < 10:      i = i+1      if i % 2 == 0:         continue      print(i, "= Hello, there!")

Ouput:

1 = Hello, there!
skipped --> i % 2 = 0
3 = Hello, there!
skipped --> i % 2 = 0
5 = Hello, there!
skipped --> i % 2 = 0
7 = Hello, there!
skipped --> i % 2 = 0
9 = Hello, there!
skipped --> i % 2 = 0

It was skipped by program because value of ‘i’ is divisible by 0.

Note: If there is an infinite loop in python, it can be solved by pressing CTRL+C.

For Loop

Syntax For loop:

for i in range (j):    program ...    program ...

According to the syntax above, the For loop is executed ‘j’ times. For each iteration, the value of ‘i’ will change its value starting from 0, 1, 2, 3, … , n-1. If it reaches this value, the loop will stop.

Example:

for i in range (4):    print("Hello World")

Ouput:

Hello World
Hello World
Hello World
Hello World

We can create different ranges. Examples like range(x, y).

for i in range (1, 4):    print("Number = ", i)

Ouput:

Number =  1
Number = 2
Number = 3

And we also can make range(x, y, z). z is step value. In range(x, y, step) has meaning the magnitude of the increase in the value of the counter variable. At first the value of counter variable is x, and then every loop the value increase number of steps. And loop will stop until the value reaches y.

Example:

for i in range (1, 4):    print("Number = ", i)

Ouput:

Number = 1
Number = 3
Number = 5
Number = 7
Number = 9

We can display odd numbers 1–20 without print command 20 times.

Script:

number = 0print("Odd Number 0 - 20")for i in range(20):    if (i % 2 == 1):    #change enter to space using end command after print    print(i, end=' ')

Output:

Odd Number 0 - 20
1 3 5 7 9 11 13 15 17 19

And we can sum multiples of 2 (even numbers) 0–20 without count up one by one.

Script:

number = 0total = 0print("Even number from 0-20")print()
for i in range(20): if (i % 2 != 1): print(i, end=' ') number = number + 1 total = total + iprint()print("Total sum of numbers:", total)print("Number of even numbers:", number)

Output:

Even number from 0-200 2 4 6 8 10 12 14 16 18Total sum of numbers: 90
Number of even numbers: 10

And we’ll create a simple program that makes triangles from stars (*).

Example 1:

for i in range (0, 4):    for j in range(0, i+1):        print("* ", end = "")    print()

Output of example 1:

* 
* *
* * *
* * * *

Example 2:

for i in range(4, 0, -1):    for j in range(1, i + 1):        print("* ", end = "")    print()

Output of example 2:

* * * * 
* * *
* *
*

After learned about loop in python, we can make a mini-game. The mini game will pick a random number from 0–100, and you have to guess the number. Each wrong answer it’ll decrease your score -2. Let’s try this script program.

Script for mini-game:

from random import randintscores = 100#pick random numbernumbers = randint(0, 100)print("Guess the numbers starting from 0-100")print()while True:   guess = int(input("Your Guess: "))   if guess > numbers:      print("Your guess is too big")      #decrease the score      scores -= 2      print()   elif guess < numbers:      print("Your guess is too small")      #decrease the score      scores -= 2      print()   elif guess == numbers:      print("Congratulations, your guess is right!!")      print()      breakprint("Your score:", scores)

You can try the script above on your own python or maybe want to change the program.

Hope this article can help for beginners python programmers. Thank you for reading. Have a nice day!

--

--

Ahmad Adli

Ahmad 'Adli Ash-Shidiqqie (K3521004), student college of Sebelas Maret University