×

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 Support

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

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

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

Convert uppercase to lowercase in Python

Python String lower() By using the built-in string lower() method, all the uppercase characters can be converted into lowercase characters in a string, The lowercased string from the given string is returned...

1 minute read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

Python Trigonometric Functions

Before jumping right into the functions and how to use them we need to know what do trigonometric functions mean and how many functions does python has. What are Trigonometric functions? Trigonometric...

3 minutes read.

Python Call Function

In this article, you will learn about calling a function in Python. But before learning this, we should know about functions in Python.So, let’s get some overview of functions in...

6 minutes read.

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

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.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

What does the if __name__ == "__main__" do in Python

In this article, you will learn about the If__name__==__main__ is a statement in python to define modules and the names of the modules. This statement plays a vital role in...

3 minutes read.

Python exit commands

exit(), quit(), sys.exit(), os._exit() In this tutorial, we will study exit commands used in the Python programming language. Python is undoubtedly the choice of programmer and this is because of the in-built...

3 minutes read.

How to create a dictionary in Python?

How to create a dictionary in python Dictionary is a data structure in Python that represents our data in the form of keys and values. Each value in a dictionary can be...

5 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.