While Loop In Python Programming Language

Python While Loop In Python Programming Language

In this tutorial, you will learn what is While loop in Python programming language and how you can use it in your code.

What is while loop in Python?

In Python programming language a while loop is used to iterate a block of code until the given condition becomes true.  Generally, in while loop, we don’t know how much time do we need to iterate.

Syntax of while Loop in Python

Here in the above syntax of while loop test_expression runs first. Only if the test_expression becomes true then the body of while loop runs. After completing one successful iteration the test_expression checked again and if it is true then the body of while loop runs again and this process goes on until the test_expression becomes false.

Recommended:  Global, Local And Nonlocal Variables In Python Programming

Body of while loop can consist of a  single line statement or a multi-line block of code. As the test_expression becomes false the control of the program passes to line right after the body of while loop.

Flowchart of while loop

Python-While-Loop-Flow Chart

Here you can see first that checked is test_expression and if it is false the while loop will be exit and all control shifts to the very next line of the loop but in case if test_expression is true the body of while loop starts to execute and it will continue until the test_expression becomes false.

Example of Python while Loop

after the above code executes the following results shows:

In the above example our python while loop continues to run as long as our variable x is less or equal to variable n(12).

Remember:   We must increase   x = x+1  counter variable. This is the most important work unless the loop never ends and continue running infinity until all the memory exhausts.

while loop with else

Python offers an optional else statement with the while loop as of with the for loop. But the else block will only run if the text_expression in a while loop becomes false.

Recommended:  Variables,Data Types and Type Conversion In Python Programming Language

Example of while loop with else statement

after the above code executes the following results shows:


Jack Sparrow

Hay I Am Admin Of This Website. I Am Very Passionate About Computers And Technology. This Website Is The Result Of My Passion. I Love To Eliminate The Barriers That Come In Seeking Education. This Website Is The Free Source Of Learning About New Technology And Up To Date Knowledge.

Leave a Reply

Close Menu