In python, you use the while statement to write a condition-controlled loop.

In the last post about Python "for" loops, we got introduced to Python's concept and how does Python handle loop. With different variations and methods introduced in loops, we are all set to move ahead to the next and probably the only other important loop in Python: python while loop. Since this is also a loop, the work needs no introduction in this post. If you are unaware, I highly recommend going through the python "for" loops and brief yourselves with the basics.

This post will cover the basics in the following fields:

  • What is the Python "While" loop?
    • Syntax of Python "while" loop.
    • How to implement while loops in Python?
    • Flowchart for Python While loops.
    • While True in Python
    • While-Else in Python
    • Python "Do While" loops.

What is the Python "While" loop?

The while loop in python is a way to run a code block until the condition returns true repeatedly. Unlike the "for" loop in python, the while loop does not initialize or increment the variable value automatically. As a programmer, you have to write this explicitly, such as "i = i + 2". It is necessary to be extra cautious while writing the python "while" loop as these missing statements can lead to an infinite loop in python. For example, if you forgot to increment the value of the variable "i" , the condition "i < x" inside "while" will always return "True". It is therefore advisable to construct this loop carefully and give it a read after writing.

The syntax for Python while loops

The syntax for python while loop is more straightforward than its sister "for" loop. The while loop contains only condition construct and the piece of indented code, which will run repeatedly.

while[condition]:
    //Code Block

The conditions can be as simple as [i < 5] or a combination of them with the boolean operators' help in python. We shall see them steadily into the post.

How to implement a while loop in Python?

To implement the while loop in Python, we first need to declare a variable in our code as follows [since initialization is not like the for loop]:

i = 1

Now I want "Good Morning" to be printed 5 times. Therefore, the condition block will look as follows:

i

Chủ Đề