How to pick a random item from an input list?

Question:

I am making a program that asks how many players are playing, and then asks to input the names of those players. Then, I want it to print a random player, but I can’t figure it out how.

The code right now prints a random letter from the last name given, I think:

import random

player_numberCount = input("How many players are there: ")
player_number = int(player_numberCount)

for i in range(player_number):
    ask_player = input("name the players: ")

print(random.choice(ask_player))
Asked By: Qstz D

||

Answers:

You need to add each player name entered to a list. Here is a starting point of what you need in your code:

from random import choice

number_of_players = int(input("How many players are there: "))
players = []

for _ in range(number_of_players):
    players.append(input("name the players: "))

print(choice(players))
Answered By: accdias

That loop reassigns the ask_player variable on each iteration, erasing the previous value.

Presumably you meant to save each value in a list:

players = []
for i in range(player_number):
    players.append(input("Player name: "))

print(random.choice(players))
Answered By: John Gordon

The problem is that in each for-loop iteration, you are reassigning the ask_player var to a string. When you pass a string to random.choice(…), it picks a random letter of that string (since strings can be indexed like arrays). Just define an array before the loop and append on each iteration:

import random

player_numberCount = input("How many players are there: ")
player_number = int(player_numberCount)

players = []
for i in range(player_number):
    players.append(input(f"name player {i + 1}: "))

print(random.choice(players))
Answered By: JustMe
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.