Ошибка по объявлению переменной

Рейтинг: 0Ответов: 1Опубликовано: 16.04.2023

Пишу программу с графическим интерфейсом на python, пока занимаюсь кодом. При указании функции creatrPassword с атрибутами 20, True, True, True, False Вылетает ошибка, что переменная TTTT не объявлена. Хотя если вызвать эту же функцию с атрибутами 20, True, True, True, True, то ничего не происходит, пароль делается правильно и без ошибок. Вот код:

import random

# Пароль

letters = "abcdefghigklmnopqrstuvwxyz"
big_letters = "ANCDEFGHIGKLMNOPQRSTUVWXYZ"
numbers = "1234567890"
symbols = ":;.-_!?/,'*-&"

def createPassword(len, let, biglet, num, sym):
    # len - показатель длины, принимаются параметры 6 - 20
    # let - переключатель букв, принимаются значения True/False
    # biglet - переключатель больших букв, принимаются значения True/False
    # num - переключатель цифр, принимаются значения True/False
    # sym - переключатель символов, принимаются значения True/False

    # Система отправки сообщений (СОС)

    if let and biglet and num and sym:
        TTTT = True
    elif let and biglet and num and not sym:
        TTTF = True
    elif let and biglet and not num and not sym:
        TTFF = True
    elif let and not biglet and not num and not sym:
        TFFF = True
    elif let and not biglet and not num and sym:
        TFFT = True
    elif let and biglet and not num and sym:
        TTFT = True
    elif let and not biglet and num and sym:
        TFTT = True
    elif let and not biglet and num and not sym:
        TFTF = True

    elif not let and not biglet and not num and not sym:
        FFFF = True
    elif not let and not biglet and not num and sym:
        FFFT = True
    elif not let and not biglet and num and sym:
        FFTT = True
    elif not let and biglet and num and sym:
        FTTT = True
    elif not let and biglet and num and not sym:
        FTTF = True
    elif not let and not biglet and num and not sym:
        FFTF = True
    elif not let and biglet and not num and not sym:
        FTFF = True
    elif not let and biglet and not num and sym:
        FTFT = True

    password_list = list()

    if TTTT:
        for i in range(len):
            type = random.randint(0, 3)
            if type == 0:
                password_list.append(str(random.choice(letters)))
            if type == 1:
                password_list.append(str(random.choice(big_letters)))
            if type == 2:
                password_list.append(str(random.choice(numbers)))
            if type == 3:
                password_list.append(str(random.choice(symbols)))
        print("".join(password_list))
    elif TTTF:
        for i in range(len):
            type = random.randint(0, 2)
            if type == 0:
                password_list.append(str(random.choice(letters)))
            if type == 1:
                password_list.append(str(random.choice(big_letters)))
            if type == 2:
                password_list.append(str(random.choice(numbers)))
        print("".join(password_list))


createPassword(20, True, True, True, False)

Ответы

▲ 0

Я сделал более производительную версию вашего кода. Он использует меньше операторов if и должен работать быстрее.

import random


def generate_password(
    length: int = 8,
    use_lowercase: bool = True,
    use_uppercase: bool = True,
    use_digits: bool = True,
    use_symbols: bool = True,
) -> str:
    """
    This function generates a randomly chosen password
    :param length:          the desired length of the password
    :param use_lowercase:   whether to use lowercase letters
    :param use_uppercase:   whether to use uppercase letters
    :param use_digits:      whether to use digits
    :param use_symbols:     whether to use symbols
    :return:                a randomly generated password
    """
    chars_to_choose_from: str = ""
    if use_lowercase:
        chars_to_choose_from += "abcdefghijklmnopqrstuvwxyz"
    if use_uppercase:
        chars_to_choose_from += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    if use_digits:
        chars_to_choose_from += "0123456789"
    if use_symbols:
        chars_to_choose_from += ":;.-_!?/,'*-&"
    if len(chars_to_choose_from) == 0:
        return ""
    if length <= 0:
        return ""
    return "".join([random.choice(chars_to_choose_from) for _ in range(0, length)])


def main():
    print(generate_password(16, use_symbols=False))


if __name__ == "__main__":
    main()