《量化投资以python为工具》第九章作业第二题P109
输入用户名:首位必须为字母
输入密码:1.首位为字母
2.长度大于6
3.必须至少含有’_’或’*’或’#’中的一个
4.必须至少含有一个数字
代码实现:
#方法一
def createuser():
fuhao = ['_', '*', '#']
while(1):
print('input username:')
username = input()
if username[0] > 'a' and username[0] < 'z':
break
else:
print('username must begin with a-z')
while(1):
print('input password:')
password = input()
if password[0] < 'a' or password[0] > 'z':
print('password must begin with a-z')
elif(len(password) <= 6):
print('the length of password must upper 6')
elif((fuhao[0] not in password) and (fuhao[1] not in password) \
and (fuhao[2] not in password)):
print('''password must at least include one of '_', '*', '#' ''')
elif(('0' not in password) and ('1' not in password) and ('2' not in\
password) and ('3' not in password) and ('4' not in password) and\
('5' not in password) and ('6' not in password) and ('7' not in\
password) and ('8' not in password) and ('9' not in password)):
print('password must at least one number')
else:
print('create successful!')
break
#方法二
def createuser2():
fuhao = ['_', '*', '#']
while(1):
print('input username:')
username = input()
if username[0] > 'a' and username[0] < 'z':
break
else:
print('username must begin with a-z')
while(1):
print('input password:')
password = input()
if len(password) <= 6:
print('the leghth of password must bigger than 6')
err1 = 0
err2 = 0
for i in range(len(password)):
if i == 0:
if password[i] < 'a' or password[i] > 'z':
print('password must begin with a-z')
if password[i] in fuhao:
err1 = 1
if password[i] >= '0' and password[i] <= '9':
err2 = 1
if err1 == 0:
print("""password must include at least one of '_', '*', '#'""")
elif err2 == 0:
print('password must at least include one of number')
else:
print('create successful!')
break
没有考虑大写字母(懒得考虑了,也简单,先将用户名和密码用lower()全部改为小写字母再判断就行)
之所以写的这么麻烦是因为想要得到输入具体不符合哪个要求。代码有些冗余,大家随时可以批评指正。