Keep the numbers in one list:
numeros = [] # lista que vai guardar os números
for i in range(1000):
n = int(input())
if i == 0 and n == -1: # se o primeiro é -1, sai do loop
break
numeros.append(n) # adicionar o número na lista
I used range(1000)
, which generates the sequence of numbers between 0 and 999 (i.e., the for
will iterate 1000 times). And I’ve included the stop rule when the first number is -1 (break
interrupts the loop). And if this occurs, the list of numbers will be empty.
I also used int
to turn what was typed into number (will give error if not typed a number, it is not clear if it is requirement of the problem).
To count how many times n
occurs on the list:
if numeros: # se a lista não está vazia
n = int(input())
cont = 0
for i in numeros:
if i == n:
cont += 1
print(f'{n} appeared {cont} times')
I understand that because it is an exercise, they probably want you to do the counting manually, as it is above. But in any case, it already exists ready in the language, through the method count
:
if numeros: # se a lista não está vazia
n = int(input())
print(f'{n} appeared {numeros.count(n)} times')
Another option to quit the program (since the statement says the program should stop) is to use sys.exit
:
import sys
numeros = []
for i in range(1000):
n = int(input())
if i == 0 and n == -1: # se o primeiro é -1, para o programa
sys.exit(0)
numeros.append(n)
# não preciso mais verificar se a lista é vazia
n = int(input())
# etc...
Like sys.exit
exits the program, I no longer need to check if the list is empty after the for
.
And of course it can also be done with while
instead of for
:
i = 0
numeros = []
while i < 1000:
n = int(input())
if i == 0 and n == -1: # se o primeiro é -1, para o programa
break # ou sys.exit(0)
numeros.append(n)
i += 1
And if the idea is to repeat several times the reading of the 1000 numbers, put everything within one loop infinite:
import sys
while True:
numeros = []
for i in range(1000):
n = int(input())
if i == 0 and n == -1: # se o primeiro é -1, para o programa
sys.exit(0)
numeros.append(n)
n = int(input())
cont = 0
for i in numeros:
if i == n:
cont += 1
print(f'{n} appeared {cont} times')
The while True
is repeated until the sys.exit
be called.
Thanks for the explanation! My way of using the while command wouldn’t work, right? You need to use 'for'''.
– Maria
@Maria You can also do it with
while
, I updated the answer by adding this option.– hkotsubo
Thank you very much! I understood perfectly!
– Maria
Just one observation: the program enters 1000 numbers several times, until, in one of these entries, the first one is -1.
– Maria
@Maria Atualizei a resposta
– hkotsubo