Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Gary Gibson
5,011 PointsError in password generator
I programmed a password generator for fun. I can get it to work fine with specific limits on length if user chooses "weak" or "medium" or "hard" for password difficulty.
import random
password_strength = input("How strong do you want your password to be: [W]eak, [M]edium, [H]ard? ").lower()
while True:
if password_strength == 'w':
password_length = 6
elif password_strength == 'm':
password_length = 12
elif password_strength == 'h':
password_length = 18
else:
continue
char_list = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*1234567890'
password = ''
for number in range(0, password_length):
random_position = random.randint(0, len(char_list)+1)
password_character = char_list[random_position]
password += password_character
print(password)
break
But when I try to sub in random ranges, I get errors half the time. How would you introduce a random element to this area?
if password_strength == 'w':
password_length = 6
elif password_strength == 'm':
password_length = 12
elif password_strength == 'h':
password_length = 18
else:
continue
1 Answer
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsHi Gary
Your error is in the for loop. See below
for number in range(0, password_length):
random_position = random.randint(0, len(char_list)-1) # change +1 to -1. Even though your length of char_list
# is 70 the index for the last character is 69 and not 70. So you want to get a random number between 0 and 69
# with the +1 you end up with a range of 0 and 70 which causes the out of index error
password_character = char_list[random_position]
password += password_character
loving the code nice one !!
Gary Gibson
5,011 PointsGary Gibson
5,011 PointsThanks, Andreas!!
And now this works...