Python while loop examples

A python while loop is a control statement that allows code to be executed repeatedly based on a given expression(Boolean). While loop in Python could be tricky for beginners.

In this post:

  • Python while loop
  • Stop/break while loop in Python
  • Python iterate list elements with while
    • try except - managing errors in while loop
  • Python while loop with multiple conditions
    • logical and vs or
    • 1 is considered as True, 0 as False
  • Python while loop read file
    • Python while loop find a line in file

Python while loop

The while loop can be used for repeating of a code if a special condition is True. For example you can iterate over the natural numbers from 3 to 7 by while loop:

num = 3
while (num < 7):
    print ('iteration:', num)
    num = num + 1

result:

iteration: 3
iteration: 4
iteration: 5
iteration: 6

Stop/break while loop in Python

Sometimes you will need to stop the loop by exception. This can be done with keyword break:

num = 3
while (num < 7):
    print ('iteration:', num)
    num = num + 1
    if num == 5:
        break

result:

iteration: 3
iteration: 4

Python iterate list elements with while

You can use while loop to iterate all items of a list in Python. Depending on your data and types the optimal way of iterating collection will be different:

mylist = ['item1', 'item2', 'item3']
i = 0
while i < len(mylist):
    print(mylist[i])
    i += 1

result:

item1
item2
item3  

managing errors in while loop

If you use this code:

mylist = ['item1', 'item2', 'item3']
while mylist[num]:
    num += 1
    print(mylist[num])

You will get error:

IndexError: list index out of range

The easiest way to manage errors like this one is using try except:

mylist = ['item1', 'item2', 'item3']
try:
    while mylist[num]:
        num += 1
        print(mylist[num])
except IndexError:
    pass

the result is:

item2
item3

Python while loop with multiple conditions

Sometimes you may need to use more than one condition in while loop for python. In this case you can use:

  • logical - and
  • logical - or
num = 1
flag = True
while (num < 10) and flag:
    print('The num is:', num)
    num = num + 1
    if num % 3 == 0:
        flag = False

result:

The num is: 1
The num is: 2  

Another example returning the modular division as flag.

num = 1
flag = True
while (num < 10) and flag:
    print('The num is:', num)
    num = num + 1
    flag = num % 3

result:

The num is: 1
The num is: 2

These examples contain three interesting points:

  • two conditional expressions - only if both of them are true than the loop body is entered

  • 1 - if you use digit 1 (or get it as result) then your loop is consider this as True. While 0 is considered as False and this will break the loop.

  • logical or vs and - if you use or instead of and then you will get different result(because only one of the expressions should be True):

    The num is: 1
    The num is: 2
    ...
    The num is: 8
    The num is: 9

Python while loop read file

If you want to read a file line by line in Python the best is to use for loop. But if you still want to use while you can do it by this code example:

f=open('C:\\user\\test.txt',"r",encoding="utf-8" )
while True:
    line = f.readline()
    print(line.replace('\n', ''))
    if line == '':
        break

result:

line1
line2
line3

Python while loop find a line in file

You can search for a specific line with while conditional statement:

f=open('/home/user/test.txt', "r",encoding="utf-8" )
flag = True
while flag:
    line = f.readline().replace('\n', '')
    if '3' in line:
        print(line)
        flag = False

result:

line3

You can check for exact match of a line with:

if line == 'line2':
    print(line)
    flag = False