In this chapter let us create a python while loop to find the odd numbers within a python list.
The loop will use the continue statement to skip the even numbers and will only put an odd number in another list which will get returned after the while loop has terminated!
a = [1,2,3,4,5,6] # a list consists of 6 elements
b = [] # empty list to use to keep the odd numbers of list a
count = 0 # loop counter as well as serves as the index of the a list
while count < len(a):
if a[count] % 2 == 0 : # yeah, all us need is not an even number
count += 1 # increase the count index on each loop
continue
else:
b.insert(0,a[count]) # always insert the odd number at position 0
count += 1 # increase the count index on each loop
print(b) # [5,3,1]
As you can see, the python len method above has been used to find the total number of elements within the a list.