Search code examples
pythonfunctional-programmingiteratorreturndivision

function that takes an iterator and returns the first element in the iterator that is divisible for 2


I want to find the function that allows me to obtain an element from an iterator and returns the elements that are divisible by two or if it is not, it will print zero, however I only get it to print nothing.

def divisible2(iterator):
   iterator = iter([1,2,3])
   for  i in iterator:
     if iterator % 2 == 0:
       print(iterator)
     if iterator % 2 != 0:
       print(iterator)

print(iterator)

Solution

  • I see that a few bug in your code, so based on your question i remake the function that will satisfy your need.

    def divisible2(iterator):
        for item in iterator:
            if item % 2 == 0:
                return item
        return 0
    
    print(divisible2([1,2,3,4]))