Python While Loop 663
Python While Loop 663
count = 1
# condition: Run loop till count is less than 3
while count < 3:
print(count)
count = count + 1
In simple words, The while loop enables the Python program to repeat a set
of operations while a particular condition is true. When the condition
becomes false, execution comes out of the loop immediately, and the first
statement after the while loop is executed.
We use a while loop when the number of iteration is not known beforehand.
For example, if you want to ask a user to guess your luck number between 1
and 10, we don’t know how many attempts the user may need to guess the
correct number. In such cases, use a while loop.
while condition:
# Block of statement(s)
Let’s see the simple example to understand the while loop in Python
count = 1
# run loop till count is less than 5
while count < 5:
print(count)
count = count + 1
Output:
Note: The loop with continuing forever if you forgot to increment counter in
the above example
Example 2: Check how many times a given number can be divided by 3 before
it is less than or equal to 10.
AD
In this example, the total iteration will vary depending on the number. when a
number of iteration is not fixed always use the while loop.
count = 0
number = 180
while number > 10:
# divide number by 3
number = number / 3
# increase count
count = count + 1
print('Total iteration required', count)
Output:
In this example, we want a user to enter any number between 100 and 500.
We will keep asking the user to enter a correct input until he/she enters the
number within a given range.
Output:
We use the if-else statement in the loop when conditional iteration is needed.
i.e., If the condition is True, then the statements inside the if block will execute
othwerwise, the else block will execute.
if condition :
block of statements
else :
block of statements
AD
Example: Print even and odd numbers between 1 to the entered number.
Output:
6 is a even number
5 is a odd number
4 is a even number
3 is a odd number
2 is a even number
1 is a odd number
There are three types of loop control statements break, continue and pass.
Break Statement
A break statement terminates the loop containing it. If the break statement is
used inside a nested loop (loop inside another loop), it will terminate the
innermost loop. Let us see the usage of the break statement with an example.
Example: Write a while loop to display each character from a string and if a
character is number then stop the loop.
name = 'Jesaa29Roy'
size = len(name)
i = 0
# iterate loop till the last character
while i < size:
# break loop if current character is number
if name[i].isdecimal():
break;
# print current character
print(name[i], end=' ')
i = i + 1
Output:
J e s a a
Continue Statement
AD
continue is a statement that skips a block of code in the loop for the current
iteration only. It doesn’t terminate the loop but continues in the next iteration
ignoring the loop’s body after it. Let us see the use of the continue statement
with an example.
In this example, we will print only letters from a string by skipping all digits
and special symbols
name = 'Jesaa29Roy'
size = len(name)
i = -1
# iterate loop till the last character
while i < size - 1:
i = i + 1
# skip while loop body if current character is not alphabet
if not name[i].isalpha():
continue
# print current character
print(name[i], end=' ')
Output:
J e s a a R o y
Pass Statement
Pass statement is a null statement. Nothing happens when the pass statement
is executed. Primarily it is used in empty functions or classes. When the
interpreter finds a pass statement in the program, it returns no operation. Let
us see the usage of the pass statement with an example.
AD
n = 4
while n > 0:
n = n - 1
pass
In the nested while loop, the number of iterations will be equal to the number
of iterations in the outer loop multiplied by the iterations in the inner loop. In
each iteration of the outer loop inner loop execute all its iteration.
while expression:
while expression:
statemen(s) of inner loop
statemen(s) of outer loop
AD
* *
* * *
* * * *
i = 1
# outer while loop
# 4 rows in pattern
while i < 5:
j = 0
# nested while loop
while j < i:
print('*', end=' ')
j = j + 1
# end of nested while loop
# new line after each row
print('')
i = i + 1
AD
We can also use for loop inside a while loop as a nested loop. Let’s see the
same example using for loop inside the while loop.
i = 1
# outer while loop
while i < 5:
# nested for loop
for j in range(1, i + 1):
print("*", end=" ")
print('')
i = i + 1
i = 1
while i <= 5:
print(i)
i = i + 1
else:
print("Done. while loop executed normally")
AD
Output:
1
2
i = 1
while i <= 5:
print(i)
if i == 3:
break
i = i + 1
else:
print("Done. while loop executed normally")
Output:
Output:
10 9 8 7 6 5 4 3 2 1 0
name = "Jessa"
i = 0
res = len(name) - 1
while i <= res:
print(name[i])
i = i + 1
AD
Output:
a
Iterate a List using while loop
Python list is an ordered sequence of items. It is ordered by index numbers
starting from 0. It is enclosed by square the ‘[]’ brackets. Here are some of the
examples of lists.
numbers = [1, 2, 4, 6, 7]
names = ["Messi", "Ronaldo", "Neymar"]
There are ways to iterate through elements in it. Here are some examples to
help you understand better.
numbers = [1, 2, 4, 5, 7]
size = len(numbers)
i = 0
while i < size:
print(numbers[i])
i = i + 1
Output:
AD
1
2
4
5
7