Python

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.

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

Last updated on Feb. 24th, 2022

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button