Python, even and odd number counting

Asked

Viewed 4,032 times

2

Create a program in Python that, for any list of integer values, gets (through functions) and prints on the screen. The number of even and odd values in the list.

I’m doing a program like this, but it doesn’t come back the right amounts, it always comes back (1,0) or (0,1).

    def contaPares(lista):
    pares = 0
    impares = 0
    for lista in range(num):
        if num % 2 == 0:
            pares = pares + 1
        else:
            impares = impares + 1
        return pares, impares





    lista = list()

q = int(input('Quantos valores haverá na lista ?'))
while q < 0:
    print('Erro')
    q = int(input('Quantos valores haverá na lista ?'))

for c in range(q):
    num = int(input('Valor:'))
    lista.append(num)

print('A quantidade de valores pares e impares são, respectivamente:',contaPares(lista))
  • 2

    I believe that here: for lista in range(num): should be: for num in lista:

3 answers

2


They are two problems and both happen within the function contaPares.

A problem is the recoil of your code.

Most programming languages such as C, C++ and Java uses keys {} to define a code block. Python uses endentation.

A block of code (body of a function, loop etc.) begins with indentation and ends with the first line without indentation. The amount of recoil depends on you, but should be consistent throughout this block.

Because of the indentation your code returned after the first iteration:

return pares, impares

Second problem was iteration:

for lista in range(num):

The correct one would be to iterate for each number in its list passed as parameter:

for num in lista:

The working code:

def contaPares(lista):
    pares = 0
    impares = 0
    for num in lista:
        if (num % 2) == 0:
            pares = pares + 1
        else:
            impares = impares + 1
    return pares, impares





lista = list() 

q = int(input('Quantos valores haverá na lista ?'))
while q < 0:
    print('Erro')
    q = int(input('Quantos valores haverá na lista ?'))

for c in range(q):
    num = int(input('Valor:'))
    lista.append(num)

print('A quantidade de valores pares e impares são, respectivamente:',contaPares(lista))

Link in Repl.it

  • Save Augusto, beautiful answer! I would know if there is any difference in performance in making pares +=1 instead of pares = pares + 1? Or is micro optimization, insignificant for python?

  • 1

    @Luizaugusto, I cannot tell you. I cannot say or deny that += be only syntactic sugar for for a number to auto add to a value. I believe that well formulated a good question here on the page.

1

You are misusing the for command:

for lista in range(num):

Note that using the loop for this way, you’re saying to scroll through the list using the last range num inserted by its input.

Example:

Your last case num = int(input('Valor:')) be it 5, you will be misinforming this: for lista in range(5).

Your correct code will look like this:

def contaPares(lista):
    pares = 0
    impares = 0

    for num in lista:
        if (num % 2 == 0):
            pares += 1
        else:
            impares += 1
    return pares, impares

lista = list()

q = int(input('Quantos valores haverá na lista ?'))
while q < 0:
    print('Erro')
    q = int(input('Quantos valores haverá na lista ?'))

for c in range(q):
    num = int(input('Valor:'))
    lista.append(num)

print('A quantidade de valores pares e impares são, respectivamente:',contaPares(lista))

I recommend reading the questions:

What is the range() function in Python for?

Using For in Python

0

From what I understand, you want to implement a script that contains a function that is able to count the number pares and ímpares from a given list.

Due to the fact that there are some errors in your code, I decided to elaborate the following code:

def pares_impares(lis):

    cont_par = cont_impar = 0
    for item in lis:
        if item % 2 == 0:
            cont_par += 1
        else:
            cont_impar += 1
    return cont_par, cont_impar


valores = list(map(int, input('Digite todos os valores: ').split()))

cont_pares, cont_impares = pares_impares(valores)

print(f'\033[32mA quantidade de números pares é: {cont_pares}')
print(f'A quantidade de números ímpares é: {cont_impares}')

Note that when we execute this code we receive the following message: Digite todos os valores:. Right now we must type all the values, in the same line, separated for a single space and press enter.

After pressing enter a list of all values will be mounted and sent to the function pares_impares. Once there, the respective list is traversed by the loop of repetition for, at the same time that each value of the respective interaction is checked whether it is par or impar. If the value is par, its quantity is accumulated in the variable cont_par and, where such value is ímpar, its quantity is accumulated in the variable cont_impar.

At the end of operations the amount of values is displayed pares and ímpares.

Example of script execution

Imagine that we wish to insert the following values: 1, 9, 2, 8, 3, 7, 4, 6, 5. So when we run the script and get the message: Digite todos os valores, we must type the following...

1 9 2 8 3 7 4 6 5

... and press enter.

From that moment the script will perform the operations described above and will show us the following result:

A quantidade de números pares é: 4
A quantidade de números ímpares é: 5

Observing

The size of the list is undefined, that is, if you want to create a list with 3 values, just type the three values and press enter. If you want to create a list with 20 values, just enter twenty values and press enter.

Browser other questions tagged

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