python输入一串字符作为密码_Python字符串、集合练习_密码校验

时间:2025-01-26 07:15:51

校验密码是否合法:

1、输入一个密码要求长度在5-10位:len()

2、密码里面必须包含:大写字母,小写字母和数字:字符串方法或者集合

3、最多输入5次:for

用字符串方法实现:

for i in range(5):

passwd = input('请输入你的密码')

num = 0 #初始化需要放在循环里,每次输入密码都需要重新初始化

lower = 0

upper =0

if len(passwd)>4 and len(passwd) <11: #判断密码长度在5-10位

for pwd in passwd: #循环字符串中的字符

if (): #字符是否是数字

num += 1

elif (): #字符是否是小写字母

lower += 1

elif (): #字符是否是大写字母

upper += 1

if num and lower and upper: #若数字、大写及小写均为真,则满足密码包含大小写字母和数字

print('密码输入成功')

else:

print('密码必须包含大小写字母及数字')

else:

print('密码长度必须在5-10位')

用isdisjoint()集合方法实现:

num = {'0','1','2','3','4','5','6','7','8','9'} #定义数字集合,因为输入的密码为字符串,所以要将数字定义为string类型

lower = {'a','b','c','d','e','f','g','h','i','g','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'} #定义小写字母集合

upper = {'A','B','C','D','E','F','G','H','I','G','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'} #定义大写字母集合

for i in range(5):

passwd = input('请输入你的密码')

pwd = set(passwd) #将字符串转化为集合

if len(passwd) >4 and len(passwd)<11: #判断密码长度在5-10位

if (num) or (lower) or (upper): #判断是否没有交集

#若输入密码集合与数字、小写、大写集合任何一个没有交集,则不满足密码包含大小写字母和数字

print('密码里面必须包含大小写字母及数字')

else:

print('密码输入成功')

break

else:

print('密码长度必须在5-10位')

用交集实现

import string

num_set=set()

upper_set = set(string.ascii_uppercase)

lower_set = set(string.ascii_uppercase)

pun = set()

for i in range(5):

passwd = input('请输入密码')

pwd = set(passwd) #将字符串转化为集合

if len(passwd) > 4 and len(passwd) < 11:

if pwd & num_set and pwd & upper_set and pwd & lower_set and pwd & pun:

print('密码合法')

break

else:

print('密码必须包含大小写字母和数字')

else:

print('密码长度必须在5-10位')