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
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.
– Woss
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.
– Glebson Santos
Have you studied lists? If so, how did you try to do?
– Woss
Forgot to create the list. Below resolve this issue quite clearly.
– Solkarped