Home > OS >  How to take a random item from an input in i in range in python
How to take a random item from an input in i in range in python

Time:12-02

I am making a program that asks how many players are playing and then asks to name the players playing. I want it to then print a random player but cant figure 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))

CodePudding user response:

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))

CodePudding user response:

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))

CodePudding user response:

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))
  • Related