题目
🧊定义 input_pswd函数,提示用户输入密码,如果用户输入长度<8,抛出异常,如果用户输入长度>=8<=15.且包含(~I@#$%&*)中的至少两个字符,返回输入的密码。
知识点
抛出异常:主动让程序崩溃。
语法🍕:
raise 异常类型
结构说明:
结构 | 说明 |
---|---|
raise | 关键字;固定写法 |
异常类型 | 可以是系统提供的异常类型(IndexError、ValueError、TypeError等),也可以是自定义类型(自定义错误类型必须是Exception的子类); |
代码
class PasswordError(Exception):
# 在错误类型中重写__str__方法,可以定制错误提示信息
def __str__(self):
return '密码输入有误!'
def input_pswd():
pswd = input('请输入密码:')
if len(pswd) < 8:
raise PasswordError
if 8 <= len(pswd) <= 15:
str1 = '(~!@#$%^&*)'
str2 = ''
for i in pswd:
if i in str1 and i not in str2:
str2 += i
if len(str2) >= 2:
return pswd
raise PasswordError
return pswd
print(input_pswd())