We Offer 100% Job Guarantee Courses (Any Degree / Diploma Candidates / Year GAP / Non-IT / Any Passed Outs). Placement Records
Hire Talent (HR):+91-9707 240 250

General

Python While Loop

Python While Loop

Introduction

Whenever you want to run an operation many times, say 1000 times, what do you thing is better? Writing the same piece of code 1000 times or trying and using the same code and just changing the parameters? When you want to run the same instruction on 1000 different objects, loops are the way to go! There are many different ways to write a loop. We will focus on a WHILE loop and how to use its python. Normally, All Programming Languages using different types of looping statements like for, while and do-while. These types of looping statements are used for checking the conditions repeatedly until the false.

Looping Statements are Follow the Steps Like

  • Initialization
  • Condition Check
  • Execution
  • Iteration

Above things used for process looping statements. In this tutorial, we will Learn

  • What is an Iteration?
  • Types of iterations
  • Basic While loop syntax and how to use it
  • How to break out of a WHILE loop or an iteration based on a condition?
  • Different kinds of while loops

What is an Iteration?

Iteration means running a block of code multiple times on different objects. This is usually based on some condition. The mechanism or the programming code which does this is called a loop.

Types of Iterations

  • Indefinite Iterations – The number of iterations or the number of times the loop has to run is not pre-defined. The required code block is run until some condition is met.
  • Definite Iterations – The number of iterations specified as soon as the loop starts or even before it.

Where does the condition come into the picture?

Each Looping method is conditional. Conditional means that the instructions that you want to run will keep on running until some condition is being met or not stops meeting. A while loop iterates or keeps running instructions until the condition it uses stop being False. In other words, it keeps running the block of code(Instructions) until the condition it gets is True.

Python While Loop

Basic While loop syntax

Let’s see how does the basic syntax of a while loop look like.

while <expr>:
<statement(s)>

<expr> in the above statement stands for a condition which the while loop will use to see whether to continue the loop or stop it. This usually involves multiple parameters which have been initialized before the while loop is initiated. As soon as it hits the while loop it will check the expression in the condition, If it is true then the code block will run. Note that While loop evaluates the expression in a Boolean context. As soon as the execution hits the last line of the code block the while loop checks the condition again. As long as the condition is True the while loop will keep on running.

While in Python

Python is normally used two forms of looping statements are for and while.

i.e for is for finite looping and while for infinite looping. but we can use both ways in both loopings.

It normally identified like a condition controlled loop(while) and collection- controlled loop(for).

General Format:

while condition:
Statements

Here in Python while loop is created using ‘while’ keyword followed with condition process.

If the condition trues it executes the statements until the condition false.

Note: For looping study before learn about the indenting process in python because here there are no curly braces for ending the blocks only used the colon(:) Operator.

Example

Here Some Examples for while loops:

i=1
while i<=5:
print(i*i)
i=i+1
print("Blast off!")

Output;

1
4
9
16
25
Blast off!

 

While with else

Python having one more type of while with else process. In the previous example condition run until true and blastoff. But here we print the same thing in else because when while is no longer in true else will call.

Example

i=1
while i<=5:
print(i*i)
i=i+1
else:
print("Blast off!")

Output:

1
4
9
16
25
Blast off!

How to use it?

Lets now loop at some examples on how to actually use them!

Now consider this Loop:-

Input

a_var = 0
while(a_var <=10):
print(a_var)
a_var = a_var + 1

Output

0
1
2
3
4
5
6
7
8
9
10

Here is what is going on in the code –

  • a_var is getting initialized to 0. As soon as it hits the expression inside while loop, it checks for the condition. In the first iteration, the condition is True, as it is lesser than 10. As the condition is true, It will start excuting the indented code block. Then it prints the value in a_var which is 0 in the first iteration. In the second line of the loop the value of a_var is incremented by 1 and the resulting value of a_var = 1.
  • When it finishes with the first iteration of the code block. It again goes to the condition in the while loop in Line 2. Here it again checks if a_var is lesser than 10 or not. As the value of a_var is 1 , the condition is True and it will again execute the code block.
  • After some iterations when the value of a_var becomes 11, the condition inside the while loop becomes False and the while loop or the iteration comes to an end.

How to break out of a WHILE loop?

In the example that we just saw, the while loop runs the code block at every iteration. What if you wanted to break out of a for loop based on some condition? Or what if you wanted to skip some numbers from being printed? Python provides 2 keywords which will help to accomplish both of the above scenarios

break

This keyword breaks or stops the execution of the while loop body. As soon as this is called, it will result in the halting of execution of the while loop and the execution will start from the next code block after the while loop.

Break Statement

Continue

Continue keyword is used to stop the current execution of the loop and skip on to the next iteration. Before jumping to the next iteration it again checks the Boolean value of the condition and only if it True, it executes it, otherwise stops it.

Continue Statement

Different kinds of while loops

 Infinite Loop

It is important to ensure that you give the correct condition. It is possible that because of the faulty logic, the while loops may go in an infinite loop as the condition may never be false.

Else statement for while loop

A while can also be used along with an else statement. In this as soon as the loops or the iterations get over, the python code will execute the else statement i.e. the code under it. It is important to know that, if there is any error or break inside the else statement then the else statement will not be executed.

Input

a_var=0
while(a_var<=10):
print(a_var)
a_var = a_var +1
else:
print('Out of loop')

Output

0
1
2
3
4
5
6
7
8
9
10
Out of loop

In the above code, as soon as a_var’s value exceeds 10, The statement in else is executed.

Single Statement Loop

The while loop can be written in a single line as well. This is particularly useful if you have single line instructions after the while loop.

Input

a_var = 0
while a_var <= 10 : print(a_var) ; a_var = a_var + 1;

Output

0
1
2
3
4
5
6
7
8
9
10

The above code is especially helpful when one wants to write precise code. All pieces of statements can be separated by a semicolon.

Related Blogs:

  1. Brief Overview of Python Language
  2. Python Career opportunities
  3. Python Break Continue
  4. Python Control Flow
  5. Python Data Types
  6. Python Dictionary
  7. Python Exception Handling
  8.  Python File
  9. Python Functions
  10. Python Substring
Besant Technologies WhatsApp