Search code examples
pythonpython-3.xstringrandomindex-error

IndexError: string index out of range while working with random module


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.


Solution

  • 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)