×

Python while loop

Loops are essential in Python or any other programming language, as they help to execute a block of code repetitively.

Sometimes, situations arise where you would need to use a piece of code again and again, but you don't want to write the same line of code multiple times so for such conditions we use Loop.

Looping statements are used to execute multiple codes or statement repeatedly until the condition specified in loops is evaluated false.

Python provides mainly two loop statements-

  1. while loop
  2. for loop

In this topic, we will explain the while loop.

while loop:

The while loop is used to execute a statement repeatedly until the condition in the loop becomes false. It is used in that situation where we do not know the number of iteration in advance.

Syntax:

while expression:
    statement 

Flow Diagram

php while loop

In the above flow diagram of while loop, firstly the given condition is checked, if the condition evaluates false, the loop will be terminated and the control will transfer to the next statement in the program after the loop.

But if the condition evaluates true, the set of statements inside the loop will be executed and then the control will transfer to the beginning of the loop for the next iteration.

Example of while loop:

Some examples of while loop are as follows:

Note: The loop contains an increment operation where we increase the value of the given variable. It is a crucial step as the while loop must have an increment or decrement operation. Otherwise, the loop will run indefinitely.

1. Write a program to print the table of a given number

 num=int(input("Enter the number")) 
#define a variable for user input 
i=0 
while i<10: 
#while loop will iterate as long as the value of i is less than 10  
    i = i + 1 
# Increment operation in i 
    c=num*i 
# Multiply resultant stored in another variable c  
    print(num,'*',i,'=',c)

Output:

 Enter the number 12
 12 * 1 = 12
 12 * 2 = 24
 12 * 3 = 36
 12 * 4 = 48
 12 * 5 = 60
 12 * 6 = 72
 12 * 7 = 84
 12 * 8 = 96
 12 * 9 = 108
 12 * 10 = 120 

2. Write a program to print hello world multiple times.

num =1
#there is a variable num in which we store an integer 1.
while num<=5:
# we print the hello world fives times until condition evaluates false
    print("Hello world")
    num=num+1
#we print out "Hello world" and increase the value of number with one.

Output:

Hello world
Hello world
Hello world
Hello world
Hello world 

3. Write a program to count the number of even or odd numbers from the given series.

number = 1
count_odd=0
count_even=0
while number<10:
    number=number+1
    if number%2==0:
        count_even=count_even+1
    else:
        count_odd=count_odd+1
print('The count of even number:',count_even)
print('The count of odd number:',count_odd)

Output:

The count of even number: 5
The count of odd number: 4 

Infinite while loop

If the given condition in while loop never becomes false, then it will become an infinite while loop and will never terminate by itself. In a while loop, any non-zero value always specifies a true condition. For example:

num=0
while num<5:
    print("hello")

Output:

Above code will print 'hello' indefinitely because inside the loop we are not updating the value of num, so the value of num will always remain 0 and the condition num < 5 will always
return true.
while True:
    print('Hello')

Output:

Infinite loop 

While loop with else statement

Python provides to use of else statement with the while loop. If the given condition becomes false, the else statement will execute. The else statement is an option to use with while loop. For example:

num = 1
while num <6:
    print(num)
    num = num+1
else:
   print("Loop is finished")

Output:

 1
 2
 3
 4
 5
 Loop is finished 

Related Topics

Rank Based Percentile GUI Calculator using Tkinter in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

3 minutes read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.

Python Encapsulation

What is meant by Encapsulation? The process of restricting access to the methods and variables so that accidental modification of data can be prevented is known as Encapsulation. The motive of Encapsulation:...

3 minutes read.

Python Functionalities of Pillow Module

This instructional exercise is about "Pillow" library, one of the significant libraries of python for picture control. Pillow library of python, is an easy to use and also open source...

14 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

Sys Module in Python

What are Modules? The Modules are the kind of files that contain Python statements and definitions. The module is known by the name of the file followed by the suffix “.py”....

5 minutes read.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

Python program to convert Celsius into Fahrenheit

Python program to convert Celsius into Fahrenheit This program explains how we can take the temperature in Celsius and convert them into Fahrenheit. Celsius Celsius, also known as centigrade, is a measurement unit...

1 minute read.

Android apps for coding in python

Nowadays, it is the generation of smartphones. The world can be seen and acknowledged with a single click on your mobile phone. Everyone uses mobile phones to do any work,...

9 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python Set symmetric_difference_update() method

Python Set symmetric_difference_update() method The set.symmetric_difference_update() method in Python updates the original set by removing items that are present in both sets and inserting the other items of the set. Syntax set.symmetric_difference_update(set1) Parameter set- This parameter represents the first...

2 minutes read.

Filter List in Python

Python: Python is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programming...

3 minutes read.

CSV Module In Python

Introduction CSV stands for "comma separated values". It is the most common and simple file structure used for storing and arranging tabular data. for example; a spreadsheet or database. It stores...

5 minutes read.

Python And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

STL in Python

Python has many libraries that are very useful and simplify many complex codes. In the same way, STL is also one of the python libraries used for reading and writing...

3 minutes read.

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of...

7 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.

Python id() function

Python id() function The id() function in Python returns an id for the specified object where all the objects in has its own unique id. Syntax id(object) Parameter object: This parameter represents any object, String, Number, List,...

1 minute read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.