Search code examples
pythonpython-3.xloopsvariablesgenerated-code

How to generate a for loop using variables?


I started learning python recently and I want to become more knowledgable and flexible with using loops.

My question is, let's say I created a list of names:

names = ('Benjamin', 'Damien', 'Dexter', 'Jack', 'lucas', 'Norman', 'Thorn', 'Bella', 'Blair',
         'Ivy', 'Lilth', 'Megan', 'Rue', 'Sabrina', 'Samara', 
         'Anthea', 'Jessica', 'Igor', 'Luther', 'Boris', 'Abel', )

and now I want to use either a for loop or a while loop (I don't know which one is the best, but from my novice experience, I feel a for loop would work better but I can't find a solution) to generate random number and make my loop generate that amount of names.

This was my code but it doesn't work.

   people_count = int(input("Enter how many names you wish to have, min 0, max 20: "))

for l in range(people_count):
     generate_random_names = random.choice(names)

print (generate_random_names)

and I only get one random name. What is missing/mistake here?

Thanks in advance!


Solution

  • In your for loop you are replacing the variable generate_random_names everytime the loops iterate. Instead maybe put them into a list. Note choice() will give you duplicate values if that's what you wish for.

    people_count = int(input("Enter how many names you wish to have, min 0, max 20: "))
    generate_random_names = []
    for l in range(people_count):
         generate_random_names.append(random.choice(names))
    
    print (generate_random_names)
    

    Now you will have a list of names

    Also you don't need a for loop to do what you want, you could use a list comprehension:

    people_count = int(input("Enter how many names you wish to have, min 0, max 20: "))
    generate_random_names = [random.choice(names) for _ in range(people_count)]
    

    Heck if you don't want to have duplicate values in new list, you can use sample which takes a collection to choose from and how many you want in the new list.

    people_count = int(input("Enter how many names you wish to have, min 0, max 20: "))
    generate_random_names = random.sample(names,people_count)
    print(generate_random_names)