While loop

Blog explains the basic of while loop

While loop is use to execute group of statements several times depending on whether a condition is true or false

Syntax

while conditions:
statements

In the above syntax, ‘statements’ can represents one or multiple statements

Interpreter first check the condition. If the condition is true, it will execute statement after colon. It then go back to check the condition and if a condition is true, statement will be executed again. When it found that condition is false, it will stop or break out of the loop

Example : Printing numbers from 0 to 10

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

In the above code, variable num is created and assigned a initial value of 0. In the second line while loop is created which check whether the value of num is less than or equal to 10.

In the first loop, value of num is 0 which means the condition is true and it will start executing statements after colon. First statement include printing current value of num which is 0. In the second line, value of num is incremented by 1.

Interpreter will go back and checks the condition. Now value of num is 1 which was incremented in the first loop. It checks the condition and found that condition is true and execute statements from inside the loop. Value of num is incremented to 2

When the value of num is incremented to 10, it will check the condition and will start executing statements from loop because the condition is true. In this loop, value of num is now incremented by 1 and it becomes 11

Now it checks the condition and found that condition is false and breaks out of the loop.

Output

0
1
2
3
4
5
6
7
8
9
10

Below is the simple example which displays word “Python’ five times using while loop

x = 1
while x <= 5:
print(x,':','Python')
x+=1

Output

1 : Python
2 : Python
3 : Python
4 : Python
5 : Python

Example 2 : Displaying all characters from a string ‘Python’

str = 'Python'
len = len(str)
x = 0
while x <= len-1:
    print(str[x])
    x+=1

Output

P
y
t
h
o
n

Example 3 : Creating a list of cities and displaying every elements using while loop

city_list = ['Mumbai','Delhi','Kolkata','Chennai','Pune']
len = len(city_list)
x = 0
while x<= len-1:
    print(city_list[x])
    x+=1

Output

Mumbai
Delhi
Kolkata
Chennai
Pune
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s