I can’t write a specific number count inside a list

Asked

Viewed 52 times

2

Hello, good afternoon everyone. I am a student in Python language and I am having difficulties in an exercise.

I developed the code that returns me a list with my numbers entered in the list, but I can’t count how many times the number 5 was typed. Would someone please help me?

numeros = []
cont = 0
while True:
    num = input('Digite um número: ')
    while not num.isnumeric():
        print('Opção inválida')
        num = input('Digite um número: ')
    else:
        numeros += num
        cont += 1
    esc = input('Deseja continuar?[S/N]: ')
    while not esc.isalpha():
        print('Opção inválida.')
        esc = input('Deseja continuar?[S/N]: ')
    else:
        if esc in 'Ss':
            print('', end='')
        elif esc in 'Nn':
            break
        else:
            print('Por favor, use apenas S ou s, N ou n, tente novamente.')
            esc = input('Deseja continuar?[S/N]: ')
print(numeros)
print(numeros.count(5))

If the code appears a bit messy here because of the formatting of the site that I do not yet master, forgive me.

2 answers

1

To simplify the explanation I will generate the same problem in a smaller code.

#MESMO PROBLEMA EM UM CÓDIGO MENOR
numeros = list()
for i in range(5):
    num = input('Digite um número: ')
    numeros.append(num)
print(numeros)
print(numeros.count(5))

What this code does is read 5 data entry, in case we ask for 5 numbers, but to facilitate the explanation and be easier to read I will not do tests with the input to see if it is really a number.

What happens is the following, the function input(), will always return a string. That is, when you add the number in the list it will be added as string unless you convert the number using the function int() or float(). As in the example below:

numeros = list()
for i in range(5):
    num = input('Digite um número: ')
    numeros.append(int(num)) # int(num) -> transforma a `string` em inteiro.
print(numeros)
print(numeros.count(5))

1


I noticed that your list consists of strings. This way, you must count the string of 5, that is to count how many times the string "5" appears. Therefore, the only thing you have to move is in the last line of your code. In this case you must replace 5 for "5".

Then the code would be:

numeros = []
cont = 0
while True:
    num = input('Digite um número: ')
    while not num.isnumeric():
        print('Opção inválida')
        num = input('Digite um número: ')
    else:
        numeros += num
        cont += 1
    esc = input('Deseja continuar?[S/N]: ')
    while not esc.isalpha():
        print('Opção inválida.')
        esc = input('Deseja continuar?[S/N]: ')
    else:
        if esc in 'Ss':
            print('', end='')
        elif esc in 'Nn':
            break
        else:
            print('Por favor, use apenas S ou s, N ou n, tente novamente.')
            esc = input('Deseja continuar?[S/N]: ')
print(numeros)
print(numeros.count('5'))

Now, if your intention is to put together a list of numbers and count a specific numerical value, you can use the following code.


cont = 0
numeros = []
while True:
    cont += 1
    while True:
        try:
            n = int(input(f'Digite o {cont}º número: '))
            break
        except ValueError:
            print('Digite apenas número inteiros!')
    numeros.append(n)

    resp = input('Desejas continuar? [S/N] ').upper()
    while (len(resp) != 1) or (resp not in 'NS'):
        print('Valor INVÁLIDO! Digite apenas ')
        resp = input('Desejas continuar? [S/N] ').upper()
    if resp == 'N':
        print(f'A lista gerada foi: {numeros}')
        v = int(input('Desejas contar qual valor da lista? '))
        print(f'O valor "{v}" aparece {numeros.count(v)} vezes na lista!')
        break

Note, that this last code mounts a list of numbers and counts a value numerical user specified.

  • I am very happy by the response of each one so far, is of great value what they do on this site. Now I can continue my studies without having to skip this exercise and better understand the logic of the promise in python.

Browser other questions tagged

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