Store read names in a list and randomly choose one of them

Asked

Viewed 205 times

1

How do I, among the students I type, he draw one within the range?

In the code below it does not draw, returns me only the last name:

from random import choice
for c in range(1, 4):
    aluno = str(input(f'Nome do {c}º aluno: '))
    lista = choice(aluno)
print(lista)
  • 2

    You are not creating a list of names; you are overwriting the name 3 times. Nor does it make sense for you to draw within the loop of repetition, as there will not yet be all possible values, the draw should be out. I recommend doing a desk test to identify these logic flaws in your codes.

  • And I know you’re overwriting, and even if there’s no logic, I’m just testing possibilities because I’m starting now. I would like to know what the code would look like for such a goal, either by creating a list through the range or by having it draw without needing a list.

  • Have you studied lists? If so, how did you try to do?

  • Forgot to create the list. Below resolve this issue quite clearly.

2 answers

2

According to the documentation, random.choice takes a sequence and returns one of the elements of this sequence (chosen randomly).

In case, you are passing the variable aluno, which is a string, and strings are also strings, each character of the same is an element (in fact each code point is an element, understand the difference between character and code point here).

So actually, when using choice passing a string, the result is one of its characters:

from random import choice
print(choice('abcdefghi')) # vai imprimir apenas uma das letras

What you need is to create a list of students' names, and only then choose one of the names randomly. So don’t use choice within the loop. Use the loop to build the list, and only then make the choice:

from random import choice

lista = [] # lista começa vazia
for c in range(1, 4):
    aluno = input(f'Nome do {c}º aluno: ')
    lista.append(aluno) # adiciona o aluno na lista

aluno_escolhido = choice(lista)
print(aluno_escolhido) # escolhe um dos alunos da lista

Another detail is that input already returns a string, so no need to do str(input(...)).

Finally, you can simplify a little more, because if you just want to add the student to the list and nothing else, you don’t need the variable aluno. The same goes for aluno_escolhido: if you’re just going to print and nothing else, you also don’t need the variable.

from random import choice

lista = [] # lista começa vazia
for c in range(1, 4):
    lista.append(input(f'Nome do {c}º aluno: ')) # adiciona o aluno na lista

print(choice(lista)) # escolhe um dos alunos da lista

Another way to build the list is by using a comprehensilist on, much more succinct and pythonic:

from random import choice

lista = [ input(f'Nome do {c}º aluno: ') for c in range(1, 4) ]
print(choice(lista)) # escolhe um dos alunos da lista
  • Exactly what I wanted, perfect, thank you very much!

  • @If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. And when I get 15 points, you can also vote in all the answers you found useful.

0

The problem with your code is that you esqueceu to create the list.

One of the right ways to solve this problem is by using the algorithm I implemented, right below.

from random import choice

# Captura e trata a quantidade de nomes a ser inseridos no sorteio
while True:
    try:
        n = int(input('Desejas inserir quantos nomes no sorteio? '))
        # Para haver sorteio são necessários, pelo menos, "2" elementos.
        if n <= 1:
            print('\033[31mValor INVÁLIDO! Digite valores maiores que "1"!\033[m')
        else:
            break
    except:
        print('\033[31mValor INVÁLIDO! Digite apenas números inteiros!\033[m')

# Cria a lista de nomes.
nomes = list()
for c in range(1, n + 1):
    nome = input(f'Digite o {c}º nome: ')
    # insere cada nome na lista.
    nomes.append(nome)

# Sorteia apenas "1" nome da lista.
sorteado = choice(nomes)
print(f'\033[32mO nome sorteado é: {sorteado}\033[m')

See how the algorithm works on Repl.it

Note that this algorithm also performs the processing of the values captured by the input.

Also note that the algorithm uses the method "choice" class "random" to carry out the draw.

Browser other questions tagged

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