Just use random.sample
, which already guarantees that there will be no repetition.
But first a detail. You are asking the user to enter 15 numbers, so you need to save all of them on the list (the way you did, only the last one is put on it). And if you’re gonna use the range
only to run something several times (and whatever the value used in the iteration), just do range(15)
.
And input
already returns a string, so do str(input(...))
is redundant and unnecessary. If you want to ensure that a number has been entered, you can use int
to convert the string to number (and capture the ValueError
if no number is entered).
Then it would look like this:
from random import sample
numeros = []
for _ in range(15):
while True:
try:
numeros.append(int(input("Digite um nº: ")))
break # interrompe o while e vai para a próxima iteração do for
except ValueError:
print('não foi digitado um número')
print("NÚMEROS ESCOLHIDOS: ", sample(numeros, 9))
In the for
i use _
, which is a Python convention to indicate that the variable is not used in loop (because I’m only interested in doing something 15 times).
Then the while
executes until a number is entered (because then it falls in the block except
). If a number is entered, it is added to the list, the break
interrupts the while
and it goes to the next iteration of for
.
Finally, having the list with the 15 numbers, I use random.sample
to obtain the 9 numbers, without repetition.
Share what you’ve tried.
– Ernesto Casanova
import Random for c in range (1, 16): n1 = str(input("Type a #: ") l = [n1] Random.shuffle(l) print(", l) print(" , ", l) print(" , "l) print(" , ", l) print(" , l) print(" ", l) print(" , ", l) print(", print(", ", l) print(" ", l)
– Aragon
I’ve tried a similar one, but it wasn’t tbm
– Aragon
Edit your question and put your code there
– Ernesto Casanova