while loop in Python

Python while loop

While loop is one which repeats  a group of statements until the condition is made False, if not made False then the loop will never end. The while loop in python is same as the while loop in other programming languages.


While working with the while loop we need to follow the following 3 steps.

  1. Initialization of counter
  2. Condition checking 
  3. Updating counter

Example:- Increment counter until counter < 5 by following above 3 steps.

Program

Input

counter = 0

while counter < 5:
    print(counter)

    counter += 1

Output

0
1
2
3
4


Infinite while loop in Python

Infinite loop is one which never ends, until it is forced to stop.

These kind of loops are mainly used in games.


There are 2 ways, by which we can create infinite while loop in python.

  1. Specifying the condition which remains True forever.
  2. Not updating the counter.

True condition in while loop

Example:- Instead of incrementing the counter, we will decrement it. which will goes till -infinity. And condition remains true forever.

Program

Input

counter = 0

while counter < 5:
    print(counter)

    counter -= 1


At the place of condition we can put True keyword, which will also work.

Program

Input

while True:
    print("Hello world")

Not updating the counter in while loop

If you don't update the counter and won't make the condition false, then the loop will continue forever.

Program

Input

counter = 0

while counter < 5:
    print(counter)


The break statement in while loop

The break statement will terminate / stop the while loop.


At a particular condition when we want to end the loop, we make use of the break keyword to terminate the loop.


Example:- terminate the loop when i = 6.

Program

Input

i = 0

while i < 10:
    if i == 6:
        break
    print(i)
    
    i += 1

Output

0
1
2
3
4
5

The continue statement in while loop

At some iteration when we want to skip the statements of a loop, we make use of the continue keyword.


When continue statement is triggered all the statements below that, in a loop will be skipped, and the next iteration continues.


Example:- In this while loop when is 'even', the print statement will be skipped, and continues with the next loop.

Program

Input

x = 0

while x < 10:
    if x%2==0:
        x += 1
        continue
    
    print(x)
    x += 1

Output

1
3
5
7
9

Can we use else clause with while loop

Yes, it's possible to combine 'while' loop and 'else' clause.


When while loop fails, 'else' statement is executed.


Example:- here the while loop fails to find the character 's'. 

Program 

Input 

x = 0

while x < 6:
    if x == 's':
        x += 1
        print("character 's' found")
    
    print(x)
    x += 1
else:
    print("character 's' not found")

Output 

0
1
2
3
4
5
character 's' not found



It won't works with break. If the 'while' loop is terminated by the break statement, then the 'else' statement will not be executed.


Example:- In this the 'while' loop is terminated by the break statement, when number 5 is detected, and the 'else' statement is not executed. 

Program 

Input 

x = 0

while x < 6:
    if x == 5:
        x += 1
        break
    
    print(x)
    x += 1
else:
    print("Loop failed, 5 not found")

Output 

0
1
2
3
4



It works with continue statement. The 'else' statement is executed after the completion of 'while' loop. 


Example:- when x is even then the Iteration is continued, and after the loop is completed the 'else' statement is executed. 

Program 

Input 

x = 0

while x < 6:
    if x%2 == 0:
        x += 1
        continue
    
    print(x)
    x += 1
else:
    print("Loop failed, 5 not found")

Output

1
3
5
Loop failed, 5 not found


Loop through a list using while loop

Here is an example, which will loop through a list.

Program

Input

a = [1, 2, 3, 4, 5, 6, 7]

counter = 0

while counter < len(a):
    print(a[counter])

    counter += 1

Output

1
2
3
4
5
6
7

Loop through a tuple using while loop

Looping through a tuple is same as, looping through a list. You can follow the above code for looping through a tuple using while loop.


Loop through a set using while loop

As set can't be accessed using index, so we have to make use of iter() method. Which will return an iterator object, by which we can access the values using index.


Here is an example.

Program

Input

a = {1, 2, 3, 4, 5, 6, 7}

counter = 0

while counter < len(a):
    print(list(iter(a))[counter])

    counter += 1

Output

1
2
3
4
5
6
7

Loop through a string using while loop

Here is an example for you, which will loop through a string.

Program

Input

a = "Hello world"

count = 0

while count < len(a):
    print(a[count])

    count += 1

Output

H
e
l
l
o
 
w
o
r
l
d

Loop through a dictionary using while loop

Fetching values while iterating through a dictionary, by making using the values() method.

Program

Input


dic = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

values = list(dic.values())

count = 0
while count < len(dic):
    print(values[count])

    count += 1

Output

1
2
3
4
5

Fetching keys while iterating through a dictionary

First fetching the keys from a dictionary using the keys() method. Converting all the fetched keys into list so that we can iterate over it using index. If we don't convert it into a list we will get an error.

Program

Input


dic = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

keys = list(dic.keys())

count = 0
while count < len(dic):
    print(keys[count])

    count += 1

Output

one
two
three
four
five


With the following program we can get the values from the fetched keys.

Program

Input

dic = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

keys = list(dic.keys())

count = 0
while count < len(dic):
    print('key: ', keys[count], ' - value: ', dic[keys[count]])

    count += 1

Output

key:  one  - value:  1
key:  two  - value:  2
key:  three  - value:  3
key:  four  - value:  4
key:  five  - value:  5

Iterate through a dictionary using items() method

The items() method will return the collection of tuple 'key: value' pairs in a list. When we iterate through it, one 'key: value' pair will be fetched with each iteration, and to fetch the 'key' specify the index '0' and index '1' to get the value.


Program

Input

dic = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

items = list(dic.items())

count = 0
while count < len(dic):
    print('key: ', items[count][0], ' - value: ', items[count][1])

    count += 1

Output

key:  one  - value:  1
key:  two  - value:  2
key:  three  - value:  3
key:  four  - value:  4
key:  five  - value:  5




Conclusion

In 'while' loop in Python, we follow 3 steps initialization of counter, condition checking and updating counter.

We have learned the use of break and continue statements with the 'while' loop.

And learned how to use else statement with the 'while' loop.

Also learned to loop through a list, tuple, set, string and dictionary.





Previous                          Next

If you have any query, feel free to ask.

إرسال تعليق

If you have any query, feel free to ask.

Post a Comment (0)