Home » Python » While Loop in Python

About Yatin

Working as a Technical Lead in the Information Technology sector where I'm primarily involved with projects based on Java/J2EE Technologies platform (such as Spring, Spring Boot, Hibernate, Redis, etc.), novel UI technologies (Angular & React), Docker, and AWS. Recently completed the AWS Solution Architect Associate Certification.

While Loop in Python

Hello in this tutorial, we will see how to use to while loop in python programming.

1. Introduction

The while loop allows the code to be executed until the given condition returns false. The while loop is also known as the pre-tested loop. It is represented by the syntax as:

Syntax

while EXPRESSION:
	STATEMENT(S)

Here the STATEMENT(S) can be a single statement or a group of statements. The while loop consists of some loop control statements such as:

  • continue: It transfers the control to the beginning of the loop for the next iteration and exits the current iteration of the loop
  • break: It brings the control out of the current loop. It is commonly used to terminate the loop when a certain condition is met
  • else: It is an optional clause and executed only when the expression evaluates to false. Make note that if an exception is thrown or the loop is terminated with the break statement the else block won’t be executed

1.1 Single statement suites

If a while loop consists of a single statement it is known as the single statement suites. We will understand with a practical example.

1.2 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

2. While Loop in Python

Let us dive in with the programming stuff now. I am using JetBrains PyCharm as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Creating an implementation file

Let us understand the implementation with the help of a python script.

Implementation file

# python while loop example

# while loop
def while_loop():
    i = 1
    while i < 11:
        print('counter = {}'.format(i))
        i += 1


# while loop with else
def while_else():
    i = 1
    while i < 6:
        print('counter = {}'.format(i))
        i += 1
    else:
        print('loop completed')


# while loop and break statement
def while_break():
    i = 1
    while i < 11:
        if i == 5:
            print('counter reached threshold. breaking loop')
            break
        else:
            print('counter = {}'.format(i))
            i += 1


# while loop and continue statement
def while_continue(brand):
    i = 0
    while i < len(brand):
        if brand[i] == 'a' or brand[i] == 'd':
            i += 1
            # skipping alphabets - 'a' and 'd'
            continue
        print('current alphabet = {}'.format(brand[i]))
        i += 1


# single statement suites
def single_statement_suites():
    flag = 1
    while flag: print('printing single statement suites'); flag -= 1

    print('done')


if __name__ == '__main__':
    # while_loop()
    # while_else()
    # while_break()
    # while_continue('android')
    # single_statement_suites()

You can uncomment the method of your choice and run this python script. If everything goes well the output will be shown in the IDE console.

Console output

==== while loop ====
counter = 1
counter = 2
counter = 3
counter = 4
counter = 5
counter = 6
counter = 7
counter = 8
counter = 9
counter = 10


==== while loop with else ====
counter = 1
counter = 2
counter = 3
counter = 4
counter = 5
loop completed


==== while loop and break statement ====
counter = 1
counter = 2
counter = 3
counter = 4
counter reached threshold. breaking loop


==== while loop and continue statement ====
current alphabet = n
current alphabet = r
current alphabet = o
current alphabet = i


==== single statement suites ====
printing single statement suites
done

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned:

  • while loop in the python programming
  • Sample programming stuff

You can download the source code of this tutorial from the Downloads section.

4. More articles

5. Download the Project

This was a tutorial to understand the while loop in python programming.

Download
You can download the full source code of this example here: While Loop in Python

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments