Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22853

IslandT: Python Tutorial — Chapter 11

$
0
0

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.


Viewing all articles
Browse latest Browse all 22853

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>