Python Loops - A Beginner's Guide by a Beginner

Ashuka AcharyaAshuka Acharya
8 min read

Hi, I am currently learning Python and i just finished exploring a very important topic — Python Loops. In this blog, I’ll share what i have learned in the simplest way possible. If you are also a beginner like me, I hope this blog helps you as much writing it helped me.

Introduction

Loops in Python are programming statements that executes a block of code until a specific condition for termination is met. Generally, in a program the statements are executed sequentially, one after the other, but in a case where a block of code is required to be executed multiple times, loops become very useful.

Real life example: In a traffic control system, the traffic lights cycles through green, yellow and red light continuously to manage the traffic flow — here a continuous loop is in action.

Flowchart of a Loop

Types of Loops in Python

There are two main loops used in Python. They are:

  1. For Loop

  2. While Loop

  3. Nested Loop

  • For Loop:

The for loops are the control flow statements that lets you repeat a block of code as long as it is in a sequence, like list, tuple or range.

Syntax:
for iter_var in sequence:
    #block of code

Here is a simple for loop that prints all the elements of a list.

animals=['lion','tiger','leopard','elephant']

for animal in animals:
    print(animal)
#Output
lion
tiger
leopard
elephant

In the above program, the for loop iterates over each elements in the list and prints them. This loops continues until all the elements in the loop have been processed.

Another example using range().

for i in range(1,6,2):
    print('Hello World')
#Output
Hello World
Hello World
Hello World

In the above program, range(1,4)→ Generates a sequence of items from index 1 to index (6-1) with a step size 2.

Looping through a string: Strings are iterable objects as they contain series of character.

for i in 'Hello':
    print(i)
#Output
H
e
l
l
o

Else in For Loops:

Python supports else in loops unlike other languages like C/C++. The else keyword specifies the block of code that is to be executed when the loop is finished.

for x in range(1,6):
  print(x)
else:
  print("The End")
#Output
1
2
3
4
5
The End

Here, the message ‘The End‘ is printed after the loop ends.

  • While Loop:

The while loop are the control flow statements that executes a block of code until the given condition is True.

Syntax:
while condition:
    #block of code

Example using while loop:

i=0
while i<3:
   print('Hi')
   i+=1
#Output
Hi
Hi
Hi

The while loop executes the block of codes inside it until the condition (i<3) is True.

Else with While Loop

The block of codes inside the else is executed when the while condition becomes false.

Here is a simple guessing game using while else statement.

import random
correct=random.randint(1,100)
count=1
guess=int (input('Guess a number: '))
while guess!= correct:
    if (guess<correct):
        print('Guess higher:')
    else:
        print('Guess lower: ')

    guess=int(input('Next guess: '))
    count+=1

else:
    print(guess,' is the correct guess.')
    print('You guessed it in',count,'times.')

In the above program, a random number is generated between 1 and 100. Then, until the guess is correct, the block of code inside the while loop is executed. On each wrong guess, it gives feedback and asks the user for another guess. Once the loop condition becomes false i.e the correct guess is made, the block of code inside the else statement is executed.

#Output
Guess a number: 20
Guess higher:
Next guess: 25
Guess higher:
Next guess: 35
Guess higher:
Next guess: 45
Guess lower: 
Next guess: 40
Guess higher:
Next guess: 43
Guess lower: 
Next guess: 42
42  is the correct guess.
You guessed it in 7 times.
  • Nested Loop:

    The use of one loop inside another loop is called a nested loop. This means one loop runs inside the body of another, allowing you to perform repeated actions in a structured way.

    The nested loops are mainly used to print patterns, work with 2D data (like rows and columns) and many more.

Syntax:
for iter_var in sequence:
   for iter_var in sequence:
       #block of code
   #block of code

while condition:
   while condition: 
       #block of code
   #block of code

In loop nesting, we can put any type of loop inside of any other type of loops in Python. For example, a for loop can be inside a while loop or vice versa.

Pattern printing using nested loops

r=int(input('Enter the number for generating a pyramid: '))

for i in range(0,r+1):
    print(' '* 2*(r-i), end='')
    for j in range(i,-1,-1):
        print(j, end=' ')
    for k in range(1,i+1):
        print(k, end=' ')
    print()
#Output
Enter the number for generating a pyramid: 3
      0 
    1 0 1
  2 1 0 1 2
3 2 1 0 1 2 3

Loop Control Statements

The loop control statements changes the execution of a program from its normal sequence. They help in skipping parts of a loop, exit the loop early and control how the loop behaves.

There are three loop control statements supported by Python. They are:

  1. Break Statement

  2. Continue Statement

  3. Pass Statement

  • Break Statement:

The break statement in Python terminates the current loop when a condition is met and transfers the execution to the statement immediately after the loop.

If you are using a nested loop, the break statement stops the execution of the innermost loop and continues the execution from the line after that loop.

Real life example: In User Authentication System, let us suppose the user have 5 attempts to enter correct password. If they enter it before all the attempts are used, then the loop is terminated using break statement.

Here is a simple example to see the use of break.

L=[1,2,3,4,5,6]
value=4
index=0

for i in L:
    if i==value:
        print('The required value is found in index',index)
        break
    index+=1
else:
    print('The required value not found')
#Output
The required value is found in index 3

In the above example, the for loop iterated through all the elements in the list L until the required value is found. Once it’s found, it prints the confirmation message and exits the loop using break statement. If not, then the else block of code would be executed.

Another example using break in nested loops.

l=10
u=30

for i in range(l,u+1):
    for j in range(2,i):
        if i % j==0:
            break
    else:
            print(i)
#Output
11
13
17
19
23
29

In the above program, the break statement stops checking a number when it's found not to be prime, so only numbers that don’t trigger break (i.e., prime numbers) reach the else and get printed out.

  • Continue Statement:

The continue statement in Python skips the current iteration of the loop i.e when the condition to execute continue statement is met then all the code following the continue statement will be skipped for the current iteration and the next iteration of the loop will begin.

In nested loop, the continue statement only affects the loop that it is placed in i.e it skips the iteration of that loop only and moves to the next iteration.

Real life example: In an alarm clock, if i want to set an alarm for 6:00 am everyday expect Saturday then, continue like logic is used to skip that day while going through all the other days.

Here is a simple example to see the use of break.

for i in range(1,6):
    if i==3:
        continue
    print(i)
#Output
1
2
4
5

In the above example, the for loop iterated through 1 to 5 and when the value of i=3, then the condition to run continue statement becomes true and it skips that iteration while going through the rest.

Another example using continue in nested loops.

for i in range(1,4):
    for j in range(1,4):
        if j==2:
            continue
        print(i,j)
#Output
1 1
1 3
2 1
2 3
3 1
3 3

In the above example, when j=2, the continue skips the inner loop for that iteration. The outer loop just runs normally. So, i 2 is never printed out as j=2 is skipped all the time.

  • Pass Statement:

The pass statement in Python is just a placeholder. It defines a block of code that are required syntactically but you don’t know what code to write yet, in this case, pass statements are used in order to maintain the structure of the program.

Here is a simple example to see the use of pass.

for i in range(1,4):
    if i==2:
        pass
    else:
        print(i)
#Output
1
3

In the above example, when i=2 pass statement is used as a placeholder as i don’t know what block of code needs to written just yet. Without pass statement, the interpreter gives an error.

Why do we actually need loop ?

The main purpose of having loops in your code is automate repetitive tasks, process multiple items, users or inputs and iterate through a sequence.

For example: In data science, you use loops to go through rows in a CSV or Excel file to clean, filter, or analyze the data.

In an e-commerce website, loops are used to display all the items to the users.


Finally, we made it through. I hope you understood the concept of having a loop in your code.

Feel free to leave a comment or a suggestion below.

2
Subscribe to my newsletter

Read articles from Ashuka Acharya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ashuka Acharya
Ashuka Acharya