Python While Loop
Python While Loop
The Python while loop allows a part of the code to be executed until the given condition
returns false. It is also known as a pre-tested loop.
It can be viewed as a repeating if statement. When we don't know the number of iterations
then the while loop is most effective to use.
while expression:
statements
Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero
value and false is 0.
i=1
While(i<=10):
print(i)
i=i+1
Output:
10
Example -2: Program to print table of given numbers.
i=1
number=0
b=9
while i<=10:
print("%d X %d = %d \n"%(number,i,number*i))
i = i+1
Output:
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
while (1):
Output:
Example 2
var = 1
while(var != 2):
Output:
Entered value is 10
Entered value is 10
Entered value is 10
Infinite time
while(i<=5):
print(i)
i=i+1
else:
Output
Example 2
i=1
while(i<=5):
print(i)
i=i+1
if(i==3):
break
else:
Output:
In the above code, when the break statement encountered, then while loop stopped its
execution and skipped the else statement.
Example-3 Program to print Fibonacci numbers to given limit
The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This
means to say the nth term is the sum of (n-1)th and (n-2)th term.
n1, n2 = 0, 1
count = 0
if nterms <= 0:
elif nterms == 1:
print(n1)
else:
print("Fibonacci sequence:")
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Output:
Fibonacci sequence:
The break is commonly used in the cases where we need to break the loop for a given
condition.
#loop statements
break;
Example 1
list =[1,2,3,4]
count = 1;
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location");
Output:
item matched
found at 2 location
Example 2
str = "python"
for i in str:
if i == 'o':
break
print(i);
Output:
while 1:
print(i," ",end=""),
i=i+1;
if i == 10:
break;
Example 3
n=2
while 1:
i=1;
while i<=10:
print("%d X %d = %d\n"%(n,i,n*i));
i = i+1;
choice = int(input("Do you want to continue printing the table, press 0 for no?"))
if choice == 0:
break;
n=n+1
Output:
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
3X1=3
3X2=6
3X3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
Syntax
#loop statements
continue
Example 1
i=0
i = i+1
if(i == 5):
continue
print(i)
Output:
1
2
10
Observe the output of above code, the value 5 is skipped because we have provided the if
condition using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped the value
5 from the code.
Example 2
str = "JavaScript"
for i in str:
if(i == 'S'):
continue
print(i)
Output: