Home > Mobile >  python 3 how to generate multiple random element in list for loops
python 3 how to generate multiple random element in list for loops

Time:05-14

I'm doing a coding exercise and it's to build a password generator. I understand I need to utilize the for loop with the list containing the elements but I'm having trouble getting multiple random elements. If the user input is 5, I'm able to generate a random letter and 5 times of the same element but I can't get it to generate 5 different elements. What code do I need to utilize to generate random elements depending on user input? I know my code and logic is incorrect but I can't figure out how else to get around this. Any feedback is much appreciated, thank you.

import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
nr_letters= int(input("How many letters would you like in your password?\n")) 
for letter in letters:
    random_letter = random.choice(letters) * nr_letters
print(random_letter)

CodePudding user response:

There could be better ways - I've just used your code. The for loop you are using is redundant.

Can do something like -

import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
nr_letters= int(input("How many letters would you like in your password?\n")) 
random_letter=''
for i in range (nr_letters):
    random_letter  = random.choice(letters)
print(random_letter)
  • Related