×

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

Simple GUI calculator using PyQt5 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...

4 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Create a Table Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.

How to implement classifiers in Python

What is classification? Classification is a type of supervised machine learning problem with a categorical target (response) variable. Given the known label in the training data, the classifier approximates a mapping...

4 minutes read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

Python sort() function

Python provides many built-in functions for solving many problems that arise in different situations in programs. One of such methods is the sort () method. In this article, the syntax...

4 minutes read.

Arithmetic Expressions in Python

What is Python Expression? Expressions are collections of operands and operators. Python expressions are translated by the Python interpreter into some value or outcome. In Python, an expression is made up...

13 minutes read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

Difference between Yield and Return in Python

Python yield statement The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns...

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.

Pointers in Python

In this tutorial, we will study what pointers are and if they have any utility in python. Now, let us understand what pointers are Pointers Pointers are special variables used to store the...

3 minutes read.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 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.

Check whether dir is empty or not in python

Python: Check if a directory is empty In this tutorial, we will study how to check whether the director (dir) is empty or not in the python programming language. First of...

3 minutes read.

Write a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

5 minutes read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

Python Interface

When creating an application, it is important to continuously keep track of its changes. As an application grows, sometimes it gets hard to manage its updates and changes. Often, you...

4 minutes read.