Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - While Loop

Python

python logo

In this tutorial we will learn about while loop in Python.

What is a loop?

A loop is a block of code that gets executed over and over again as long as the given condition is satisfied.

Why use loop?

We use loop to complete repeating task with ease.

Imagine you have to print "Hello World" text 1000 times.

You can write the print statement 1000 times which we both know is very tiring and not the best way to solve the problem.

So, to solve this task we take help of a loop that executes the print statement for us for 1000 or N number times.

The while syntax

We use the while keyword to create a while loop in Python.

Following is the while loop syntax.

while condition:
  #
  # while loop body
  #

Where, condition is some condition and if it is satisfied then the body of the while loop is executed otherwise, it is ignored.

Inside the body of the while loop we keep updating the condition of the loop so that we can come out of it.

Example #1

In the following Python program we are printing integer number 1 to 10 using while loop.

# initialise
x = 1

# loop
while x <= 10:
  
  # print the value
  print(x)

  # update
  x += 1

print("End of code.")

The above code will print the following output.

1
2
3
4
5
6
7
8
9
10
End of code.

Explanation:

We start by initialising the variable x = 1.

For the condition we are checking is x <= 10. So, as long as value of x is less than or equal to 10 we are going to execute the body of the loop.

Inside the body of the while loop we are printing the value of x. Then we are incrementing the value of x by 1.

After incrementing the value of x we are again checking the loop condition and repeating the body.

When the value of x becomes 11 the condition fails so we come out of the while loop.

Example #2

In the following Python code we are printing only the odd numbers between 1 to 20 both inclusive.

# initialise
i = 1

# loop
while i <= 20:
  
  # check for odd number
  if i % 2 != 0:
    print(i)

  # update
  i += 1

print("End of code.")

The break statement

We use the break keyword to come out of the while loop body even if the condition of the loop is satisfied.

Example #3

In the following Python program we are going to print integer numbers from 1 to 10 but we will jump out of the while loop when we encounter number 7.

# initialise
x = 1

# loop
while x <= 10:

  # check condition
  if x == 7:
    break
  
  # output value of x
  print(x)

  # update
  x += 1

print("End of code.")

The above code will print from 1 to 6. When the value of x = 7 then the break statement will be executed and we will jump out of the while loop body.

Following is the output of the above code.

1
2
3
4
5
6
End of code.

The continue statement

We use the continue keyword to skip the current iteration and move to the next.

Example #4

In the following Python program we are printing integer number from 1 to 10. If the number is 7 then we are skipping it using the continue statement.

# initialise
x = 0

# loop
while x < 10:

    # update
    x += 1

    # check condition
    if x == 7:
        continue

    # output value of x
    print(x)

print("End of code.")

In the above code we are starting by initialising x = 0.

Inside the body of the while loop we are first increasing the value of x by 1. Then we are checking is x equal to 7. If it is 7 then we will skip the printing part. Otherwise, we will print the value of x and repeat.

So, the above code will give us the following output.

1
2
3
4
5
6
8
9
10
End of code.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT