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.

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. 

Learn data analytics courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

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. 

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. Learn more about the course.

Prepare for a Career of the Future

0 replies on “Python While Loop Statements: Explained With Examples”

Accelerate Your Career with upGrad

Our Best Data Science Courses

×