Reputation: 61
I'm making password generator in python and this is the error I'm stuck with. Here's my code:
import random
symbols = 'qwertyuiopasdfghjklzxcvbnm'
choosing_len = int(input('> '))
def password_generating():
def random_letter():
zero = 0
lenght = len(symbols)
letter_index = random.randint(zero, lenght+1)
random_symbol = symbols[letter_index]
return random_symbol
password = []
while len(password) != choosing_len:
key = [random_letter()]
password = password + key
print(''.join(password))
password_generating()
I have to say the error shows up very randomly (it almost never shows on 6). I tried to analyze it step by step and removing some code parts. nothing helps.
Upvotes: 1
Views: 193
Reputation: 14536
The error is here:
letter_index = random.randint(zero, lenght+1)
Unlike range(a, b)
, that gives numbers from a upto b, not including b, i.e. a <= x < b
, random.randint(a, b)
gives a random integer from a <= x <= b
. To correct this, we can just use
letter_index = random.randint(zero, lenght - 1)
Or even better,
random_symbol = random.choice(symbols)
Upvotes: 4