📜  python 生成随机密码 - Python 代码示例

📅  最后修改于: 2022-03-11 14:46:48.399000             🧑  作者: Mango

代码示例6
from random import choice
from string import printable # variable in the module that contains all the possible chars

# This is optional__________________
class LengthError(Exception):
    pass


def length_checker(length):
    if length < 6 or length > 40:
        raise LengthError("Password length must be between 6 and 40 characterse.")
#_______________________________________

# removing unwanted characters
chars = list(printable)
chars.pop(85)
for i in range(5):
    chars.pop()


while True: #loop (optioanl)
    try:
        print("Enter your password length:")
        max_length = int(input())
        if max_length == 0:
            exit()
        length_checker(max_length) # optional
        password = ""
        for i in range(max_length):
            password += choice(ascii_characters)
        print(f"Your generated password:{password}")
    except LengthError as e: # optional
        print(e)
    except ValueError:
        print("We can't process this with letters, symplos, emptyspaces or any other non-integer type. Please enter a valid range.")