while

The while loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed as long as the given condition is true.

It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance.

The syntax is given below.

snippet
while expression:
	statements

Here, the statements can be a single statement or the group of statements. The expression should be any valid python expression resulting into true or false. The true is any non-zero value.

Python while loop

Example 1

snippet
i=1;
while i<=10:
    print(i);
    i=i+1;

Output:

Output
1 2 3 4 5 6 7 8 9 10

Example 2

snippet
i=1
number=0
b=9
number = int(input("Enter the number?"))
while i<=10:
    print("%d X %d = %d \n"%(number,i,number*i));
    i = i+1;

Output:

Output
Enter the number?10 10 X 1 = 10 10 X 2 = 20 10 X 3 = 30 10 X 4 = 40 10 X 5 = 50 10 X 6 = 60 10 X 7 = 70 10 X 8 = 80 10 X 9 = 90 10 X 10 = 100

Infinite while loop

If the condition given in the while loop never becomes false then the while loop will never terminate and result into the infinite while loop.

Any non-zero value in the while loop indicates an always-true condition whereas 0 indicates the always-false condition. This type of approach is useful if we want our program to run continuously in the loop without any disturbance.

Example 1

snippet
while (1):
    print("Hi! we are inside the infinite while loop");

Output:

Output
Hi! we are inside the infinite while loop (infinite times)

Example 2

snippet
var = 1
while var != 2:
    i = int(input("Enter the number?"))
    print ("Entered value is %d"%(i))

Output:

Output
Enter the number?102 Entered value is 102 Enter the number?102 Entered value is 102 Enter the number?103 Entered value is 103 Enter the number?103 (infinite loop)

Using else with Python while loop

Python enables us to use the while loop with the while loop also. The else block is executed when the condition given in the while statement becomes false. Like for loop, if the while loop is broken using break statement, then the else block will not be executed and the statement present after else block will be executed.

Consider the following example.

snippet
i=1;
while i<=5:
	print(i)
	i=i+1;
else:print("The while loop exhausted");

Output:

Output
1 2 3 4 5 The while loop exhausted

Example 2

snippet
i=1;
while i<=5:
	print(i)
	i=i+1;
	if(i==3):
		break;
else:print("The while loop exhausted");

Output:

Output
1 2
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents