Number of odd numbers

Asked

Viewed 252 times

1

I created a function that returns the odd numbers. How do I return the amount of numbers, for example 4 odd, 3 odd, and so on?

lista = [1,3,5,7,2,4]
impar =[]

def ehImpar(impar):
    for impar in lista:
        if impar % 2 != 0:
            print(impar)

print(ehImpar(impar))

3 answers

3

Using list comprehensions

impar = len([i for i in lista if i%2 != 0])

Now if you want a role

def impar(lista):
   return len([i for i in lista if i%2 != 0])

If you want to read more about list comprehensions, read this article

  • Good, Luis. Thank you, really!!

  • @edtech if the answer met you consider giving the acceptance (click on "Thick Sign")

2

You can make a counter.

lista = [1,3,5,7,2,4]
impar =[]

def ehImpar(impar):
  impares = 0 
  for impar in lista:
    if impar % 2 != 0:
        impares += 1
        print(impar)
   print(impares " números ímpares")
  • Thank you very much, Davis.

0

You can change the function to add odd numbers to your list, and at the end of the iteration return the list size:

    for i in lista:
        if i % 2 !=0:
            print(i)
            impar.append(i)
    return 'Ímpares:{}'.format(len(impar))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.