×

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 list() | List class in Python

The list() class in Python creates a list object where the list object is a collection which is ordered and changeable. Syntax class list([iterable]) Parameter Iterable: It is a required parameter which represents a sequence, collection...

1 minute read.

Python Recursion

Recursion is one of the most interesting yet important concepts of any programming language. If you want to be a good programmer or data scientist, then you should better have...

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

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

Python Examples

In this tutorial, we will see some examples related to python. This will include some basic example questions and their code in Python. Write a program to print “Hello Python”. print(‘Hello Python’) Output Hello...

5 minutes read.

PyDev with Python IDE

What is IDE? Integrated Development Environment is the abbreviation of IDE. It is a coding tool that automates code editing, finding errors and testing. IDE combines all the developer tools into...

3 minutes read.

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal We know that the most widely used number system is a decimal system, but the computer only understands binary values. The...

2 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it. Linear regression One of the simplest and most widely used Machine Learning...

4 minutes read.

Iterate a Dictionary in Python – Part 2

In this tutorial, we will learn above various methods used to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to...

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.

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary In Python, dictionaries are a useful and commonly used data structure in...

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.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.

Python Tuple index() Method

Python Tuple index() Method The tuple.index() method of Python finds the first occurrence of the specified value and returns its index if the value is found else raises an exception if...

1 minute read.

Python List pop() method

Python List pop() method The list.pop() method removes the item at the specified position in the list, and return it. If no index is specified, this method removes and returns the last item in the list. Syntax list.pop([i]) Parameter i:...

1 minute read.

Python Project Ideas

One of the most widely used programming languages today is Python. This pattern appears set to continue through 2023 and beyond. Therefore, working on some current Python project ideas is the...

10 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.