mardi 28 février 2023

How to take a string, create a list from string, and select randomly from that list (x) times

I want to create a Python function which will take names as input separated by commas; turn that string into a list, and finally choose (num - parameter) number of names from that list.

I am using random.choice(list), but instead of the function printing out (num) number of names from the list, the list itself is simply being printed (num) number of times instead. I can't figure out what I am doing wrong. This is my first ever question on Stack Overflow.

  • I am importing random module
  • I am using split to delineate names by commas
  • (num) parameter should help print randomly chosen names (num) times

Here is my code and also the output:

import random

def listgen(num):
    newlist=[oglist.split(',')]
    for x in range(num):
        print(random.choice(newlist))

print("Type in your list. Separate each name by a comma and press enter when finished")
oglist=input()

print("how many random names do you need?")
num=int(input())

listgen(num)

Output:

Type in your list. Separate each name by a comma and press enter when finished

Joe, Frank, Janet, Dion, Rachel, Lilly, Alyx

how many random names do you need?

3

['Joe', ' Frank', ' Janet', ' Dion', ' Rachel', ' Lilly', ' Alyx']

['Joe', ' Frank', ' Janet', ' Dion', ' Rachel', ' Lilly', ' Alyx']

['Joe', ' Frank', ' Janet', ' Dion', ' Rachel', ' Lilly', ' Alyx']




Aucun commentaire:

Enregistrer un commentaire