Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading