While Loop In Python Programming Language

Python While Loop

In this tutorial, you will learn what is Python while loop 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:  Basic Operators In Python Programming Language

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

Flowchart-of-while-loop

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:

Recommended:  Structuring In Python Programming Language

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 comes in the for seeking education. This website is the free source of learning about new technology and up to date knowledge.

Leave a Reply

Close Menu