python - 有没有更好的验证密码的方法?
问题描述
我正在检查我的密码是否符合此条件
- 长度至少为 10 个字符
- 至少包含 1 个大写字母
- 至少包含 1 个数字
- 至少包含字符 $、#、%、& 或 * 之一
- 不包含任何空格
我的代码:
password = input("enter a password ")
def passwordIsOk (password):
symbols = "$#%&*"
if len (password) > 10:
if any(i.isupper() for i in password):
if any(i.isdigit() for i in password):
if " " not in password:
for i in range(0,5):
if symbols[i] in password:
passwordValid = True
if passwordValid == True:
print("ok buddy")
else:
print("Password must contain $#%&*")
else:
print("Password must not contain spaces")
else:
print("Password must have at least 1 number")
else:
print("Password must have at least 1 capital letter")
else:
print("Password must be greater than 10 characters")
passwordIsOk(password)
它有效,但感觉不对:(
解决方案
if
您可以通过反转条件来避免这种嵌套结构。这使代码更具可读性,并将错误消息放在检查这些错误的条件旁边。
def passwordIsOk(password):
symbols = "$#%&*"
if len (password) <= 10:
print("Password must be greater than 10 characters")
elif not any(i.isupper() for i in password):
print("Password must have at least 1 capital letter")
elif not any(i.isdigit() for i in password):
print("Password must have at least 1 number")
elif " " in password:
print("Password must not contain spaces")
elif not any(s in password for s in symbols):
print("Password must contain at least one of " + symbols)
else:
print("ok buddy")
password = input("enter a password ")
passwordIsOk(password)
推荐阅读
- sql - 计算列中的特定字符
- html - 包含使用 jQuery 的 header.html 和丢失的 CSS 格式
- asp.net-core - 用于 netcore 3.1 WebApi 问题的自定义 OData 格式化程序
- node.js - 为什么 axios fetch 在移动设备上不起作用?
- raspberry-pi - 具有屏幕读取 GPIO 和 i2c 的嵌入式 Raspberry Pi 的应用设计建议
- android - 在Android中使其可见时不可见的布局不可见
- php - 如何仅向具有特定角色用户的登录用户提供内容?
- python - 如何将多个值保存到 csv 文件中?
- python - 不明白为什么我的程序不起作用
- dns - 无法在 IBM Cloud 上创建超过 255 个字符的 DNS TXT 记录