Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Science USbreadcumb forward arrow iconPython While Loop Statements: Explained With Examples

Python While Loop Statements: Explained With Examples

Last updated:
23rd Jun, 2021
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Python While Loop Statements: Explained With Examples

Python is a robust programming language that offers many functionalities. One of those functionalities is loops. Loops allow you to perform iterative processes with very little code. 

In the following article, we’ll look at the while loop Python statement and learn how you can use it. We will also cover the various ways you can use this statement and what other functions you can combine with this statement. If you are a beginner in python and data science, upGrad’s data science certification can definitely help you dive deeper into the world of data and analytics.

Let’s get started. 

What is a While loop Python Statement?

A while loop in Python runs a target repeatedly until the condition is true. In programming, iteration refers to running the same code multiple times. When a programming system implements iteration, we call it a loop.

Ads of upGrad blog

The syntax of a while loop is:

while <expression>:

<statement(s)>

Here, <expression> refers to the controlling expression. It usually has one or more variables that get evaluated before beginning the loop and get modified in the loop body. The <statement(s)> refers to the blocks that get executed repeatedly. We call them the body of the loop. You denote them by using indentation, similar to if statements. 

When you run a while loop, it first evaluates <expression> in Boolean. If the controlling expression is true, the loop body will execute. After that, the system checks <expression> again, and if it turns out to be true again, it will run the body again. 

This process repeats until <expression> becomes false. When the controlling expression becomes false, the loop execution ends, and the code moves on to the next statement after the loop body, if there is any. 

The following examples will help you understand the while loop better:

Example 1: 

Input: 

n = 7

while n > 0:

n -= 1

print(n)

Output: 

6

5

4

3

2

1

0

Let’s explain what happened in the above example.

Initially, n is 7, as you can see in the first line of our code. The while statement header’s expression in the second line is n is greater than 0. That’s true, so the loop gets executed. Inline three, we see that n is decreased by 1 to 6, and then the code prints it. 

When the loop’s body has been completed, the program execution goes back to the loop’s top (i.e., the second line). It evaluates the expression accordingly and finds that it’s still true. So, the body is executed again, and it prints 5. 

This process will continue until n becomes 0. When that happens, the expression test will be false, and the loop will terminate. If there was another statement after the loop body, the execution would continue from there. However, in this case, there isn’t any statement so that the code will end. 

Example 2: 

Input: 

n = 1

while n > 1:

n -= 1

print(n)

There is no output in this example. 

In this example, n is 1. Notice that the controlling expression in this code is false (n > 1), so the code never gets executed. A while loop Python statement never executes if its initial condition is false. 

Example 3: 

Consider the following example:

Input:

a = [‘cat’, ‘bat’, ‘rat’]

while a: 

print(a.pop(-1))

Output:

rat

bat

cat

When you evaluate a list in Boolean, it remains true as long as it has elements in it. It becomes false when it is or if it becomes empty. In our example, the list ‘a’ is true until it has the elements ‘cat’, ‘bat’, and ‘rat’. After removing those elements using the .pop() technique, the list will become empty, making ‘a’ false and terminating the loop. Read about python while loop statements.

Using the Break Statement

Suppose you want to stop your loop in the middle of its execution even though the while condition is true. To do so, you’ll have to use the break statement. The break statement would terminate the loop immediately, and the program execution would proceed to the first statement after the loop body. 

Here’s the break statement in action: 

Example 4: 

Input: 

n = 7

while n > 0:

n -= 1

if n ==3:

break

print(n)

print(‘Loop reached the end.’)

Output:

6

5

4

Loop reached the end. 

When n became 3, the break statement ended the loop. Because the loop stopped completely, the program moved on to the next statement in the code, which is the print() statement in our example. 

Using the Continue Statement

The continue statement allows you to stop the current loop and resume with the next one. In other words, it stops the current iteration and moves onto the next one. 

The continued statement makes the program execution re-evaluate the controlling expression while skipping the current iteration. 

Example 5:

Input: 

n = 7

while n > 0:

n -= 1

if n ==3:

continue

print(n)

print(‘Loop reached the end.’)

Output: 

6

5

4

2

1

Loop reached the end. 

When we used the continue statement, it terminated the iteration when n became 3. That’s why the program execution didn’t print 3. On the other hand, it resumed its iteration and re-evaluated its condition. As the condition was still true, the program execution printed further digits until n became false, after which it moved onto the print() statement after the loop. 

Using the else statement 

One of Python’s exclusive features is the use of the else statement. Other programming languages lack this feature. The else statement allows you to execute code when your while loop’s controlling expression becomes false. 

Keep in mind that the else statement will only get executed if the while loop becomes false through iterations. If you use the break statement to terminate the loop, the else statement wouldn’t be executed. 

Example 6: 

Input: 

n = 10

while n < 15:

print (n, “is less than 15”)

n += 1

else:

print (n, “is not less than 15”)

Output: 

10 is less than 15

11 is less than 15

12 is less than 15

13 is less than 15

14 is less than 15

15 is not less than 15

Become an expert in Python and Data Science

The while loop is one of the many tools you have available in Python. Python is a vast programming language and is the preferred solution among data scientists. Learning Python and its various concepts, along with data science all by yourself, can be tricky. 

That’s why we recommend taking a data science course. It will help you study the programming language in the context of data science with the relevant technologies and concepts. 

At upGrad, we offer the Executive PG Programme in Data Science. This is a 12-month course that teaches you 14+ programming tools and languages. It is a NASSCOM validated first Executive PGP in India, and we offer this program in partnership with the International Institute of Information Technology, Bangalore.

The program offers you six unique specializations to choose from:

  • Data science generalist
  • Deep learning
  • Natural language processing
  • Data engineering
  • Business analytics
  • Business intelligence/data analytics

Some of the crucial concepts you’ll learn in this program include machine learning, data visualization, predictive analysis with Python, natural language processing, and big data. You only need to have a bachelor’s degree with at least 50% or equivalent passing marks. This program doesn’t require you to have any prior coding experience. 

upGrad has a learner base of over 40,000 learners in over 85 countries. Along with learning necessary skills, the program will allow you to avail of peer-to-peer networking, career counselling, interview preparation, and resume feedback. 

Ads of upGrad blog

These additional features will allow you to kickstart your Python and data science career much easier. 

Conclusion

The while loop Python statement has many utilities. When combined with the break and the continue statements, the while loop can efficiently perform repetitive tasks. 

Be sure to practice the loop in scenarios to understand its application properly. If you’re eager to learn more, check out the article we have shared above. It will help you significantly in your career pursuit.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.
Get Free Consultation

Select Coursecaret down icon
Selectcaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Data Science Courses

Frequently Asked Questions (FAQs)

1How is a while loop different from a for loop?

The following illustrates the key difference between a while loop and a for loop.
For Loop - The syntax is - for i in sequence: statements(s) If the condition is not mentioned, the loop will execute infinitely. The number of iterations is pre-defined.

While Loop - The syntax is - while expression: statement(s) The loop will throw an error in the absence of a condition. The loop iterates until the loop condition returns true.

2What are the main components of a “while loop” in Python?

The basic structure of a “while loop” block contains 4 main steps- initiation, loop condition, loop body, and update loop variable.
1. Initiation of Loop Variable: This step includes initializing a variable that will be used to iterate the loop. Such variables are also known as control variables. The initiation step is done before starting the loop block.
2. Loop Condition:This condition generates a Boolean result; the loop body executes only when this condition evaluates to true.
3. Loop Body: The loop body is made up of the statements that are written inside the loop block. These statements are executed when the loop condition is true.
4. Update Loop Variable: In this step, the value of the control variable is updated to run the next iteration of the loop.

Explore Free Courses

Suggested Blogs

Top 10 Real-Time SQL Project Ideas: For Beginners &#038; Advanced
14859
Thanks to the big data revolution, the modern business world collects and analyzes millions of bytes of data every day. However, regardless of the bus
Read More

by Pavan Vadapalli

28 Aug 2023

Python Free Online Course with Certification [US 2024]
5519
Data Science is now considered to be the future of technology. With its rapid emergence and innovation, the career prospects of this course are increa
Read More

by Pavan Vadapalli

14 Apr 2023

13 Exciting Data Science Project Ideas &#038; Topics for Beginners in US [2024]
5474
Data Science projects are great for practicing and inheriting new data analysis skills to stay ahead of the competition and gain valuable experience.
Read More

by Rohit Sharma

07 Apr 2023

4 Types of Data: Nominal, Ordinal, Discrete, Continuous
6060
Data refers to the collection of information that is gathered and translated for specific purposes. With over 2.5 quintillion data being produced ever
Read More

by Rohit Sharma

06 Apr 2023

Best Python Free Online Course with Certification You Should Check Out [2024]
5626
Data Science is now considered to be the future of technology. With its rapid emergence and innovation, the career prospects of this course are increa
Read More

by Rohit Sharma

05 Apr 2023

5 Types of Binary Tree in Data Structure Explained
5385
A binary tree is a non-linear tree data structure that contains each node with a maximum of 2 children. The binary name suggests the number 2, so any
Read More

by Rohit Sharma

03 Apr 2023

42 Exciting Python Project Ideas &#038; Topics for Beginners [2024]
5854
Python is an interpreted, high-level, object-oriented programming language and is prominently ranked as one of the top 5 most famous programming langu
Read More

by Rohit Sharma

02 Apr 2023

5 Reasons Why Python Continues To Be The Top Programming Language
5339
Introduction Python is an all-purpose high-end scripting language for programmers, which is easy to understand and replicate. It has a massive base o
Read More

by Rohit Sharma

01 Apr 2023

Why Should One Start Python Coding in Today’s World?
5220
Python is the world’s most popular programming language, used by both professional engineer developers and non-designers. It is a highly demanded lang
Read More

by Rohit Sharma

16 Feb 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon