I seem to have run into wall here. It keeps showing an Index Error at line "unordered_letter[letter] = random.choice(letters[nr_letters – 1])". My inexperienced eyes are unable to catch the issue so kindly help with the same. Thanks in advance!
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']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the PyPassword Generator!")
nr_letters = int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
unordered_letter = []
for letter in range(0, nr_letters):
unordered_letter[letter] = random.choice(letters[nr_letters - 1])
print(unordered_letter)
>Solution :
Change:
for letter in range(0, nr_letters):
unordered_letter[letter] = random.choice(letters[nr_letters - 1])
To this:
for letter in range(0, nr_letters):
unordered_letter.append(random.choice(letters))
Change #1:
Use the .append() function. Your original code produces an error since you are trying to set a value to a nonexistent index since your array is empty.
Change #2:
Change random.choice(letters[nr_letters - 1]) to random.choice(letters) if you want to produce a variety of letters rather than one singular letter. Your original code will only append the nr_letters - 1th element of letters, while this new code will choose random elements from letters.
Use the same process for symbols and numbers.