×

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

Python String upper() method

Python String upper() method The string.upper() method in Python returns a copy of the string converted to uppercase. Syntax string.upper() Parameter NA Return This method returns a copy of the string converted to uppercase. Example 1 # Python...

1 minute 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.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 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 Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

How to read data from com port in python

Comport, the I/O interface is known as a COM port that allows the connection for a serial device to a computer. COM ports are sometimes referred to as serial ports....

3 minutes read.

Python hex() function

Python hex() function The hex() function in Python  converts the specified number into a hexadecimal value. Syntax hex(x) Parameter x: The parameter represents an Integer value. Return This function Returns hexadecimal string. Example 1 # Python Program explaining # the hex() function print("The...

1 minute read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

How To Take Multiple Inputs In Python

In C language, we make use of the scanf() function to obtain the values from the user and store it in the variable. Coming to the Python language, we use the...

5 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

Python String find() method

Python String find() method The string.find() method in Python finds the first occurrence of the specified value and returns the lowest index in the string if the substring sub is found else it...

2 minutes read.

Gaussian elimination in python

Linear and polynomial equations are used in almost all fields of numerical simulation. However, its most common use in engineering is in the area of linear system analysis. The broader...

3 minutes read.

How to comment out a block of code in Python

When you are writing code in Python, you may want to document it. You need to mention why a piece of code functions, for instance. Mathematics, algorithms, and intricate business...

4 minutes read.

Python String istittle() method

Python String istittle() method The string.istittle() method returns a boolean value true if the string is a titlecased string and there is at least one character, for example uppercase characters may...

2 minutes read.

How to Install Tweepy in Python

In this article, we will learn or understand how to install Tweepy in Python and what Tweepy is. Firstly, let’s understand What Tweepy is. As we all know, one of the...

3 minutes read.