#1、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者
def func(l):
return l[1::2]
print(func([1,2,3,4,5,6]))
#2、写函数,判断用户传入的对象(字符串、列表、元组)长度是否>5
def func(x):
return len(x)>5 #计算的表达式都是一个布尔表达式,结果是一个True/False
print(func([1,2,3,4]))
#3、写函数,检查传入列表的长度,如果大于2则保留前两个长度的内容,并将新内容返回
def func(l):
return l[:2] #切片的长度如果大于原序列的长度,不会报错,有多长且多长
print(func([1]))
#4、写函数,计算传入字符串中 数字、字母、空格、其他字符的个数,并返回结果
def func(s):
dic = {‘num‘:0,‘alpha‘:0,‘space‘:0,‘others‘:0}
for i in s:
if i.isdigit():
dic[‘num‘] += 1
elif i.isalpha():
dic[‘alpha‘] += 1
elif i.isspace():
dic[‘space‘] += 1
else:
dic[‘others‘] += 1
return dic
print(func(‘sfd345 fsd gdh -=-a=x‘))
#5、写函数,检查用户传入的对象的每一个元素是否含有空内容,并返回结果
def func(x):
if x and type(x) is str:
for i in x:
if i == ‘ ‘:
return True
elif x and type(x) is list or type(x) is tuple:
for i in x:
if not i:
return True
elif not x:
return True
else:
return True
print(func([1,2,3,‘hhhj ‘]))
#6、写函数,检查传入的字典的每一个value的长度,如果大于2,那个保留前两个长度的内容,并返回新内容
def func(dic):
for k in dic:
if len(dic[k]) >2:
dic[k] = dic[k][:2]
return dic
print(func({1:‘wangjing‘,2:[1,2,3,4]}))
#7、写函数,接收2个数字参数,返回比较大的数字
def func(a,b):
return a if a>b else b #max(a,b)
print(func(5,4))
#8、写函数,用户传入修改的文件名 与 要修改的内容,执行函数,完成整个文件的批量修改操作
def func(file,old,new):
with open(file,mode=‘r‘,encoding=‘utf-8‘) as f1, open(‘{}.bak‘.format(file),mode = ‘w‘,encoding = ‘utf-8‘) as f2:
for line in f1:
if old in line:
line = line.replace(old,new)
f2.write(line)
import os
os.remove(file)
os.rename(‘{}.bak‘.format(file),file)
func(‘wj_file‘,‘wangjing‘,‘wangxiao‘)
‘‘‘
作业
1、先注册,注册结果写到txt文件,并打印
2、三次登录,读取文件验证
‘‘‘
def register():
user = ‘‘
while 1:
name = input(‘请输入您的用户名:‘)
if name.upper() == ‘Q‘:
print(‘结束注册,请登录‘)
break
pwd = input(‘请输入您的密码:‘)
if pwd.upper() == ‘Q‘:
print(‘结束注册,请登录‘)
break
elif len(name) <= 10 and len(name) >= 6 and len(pwd) <= 10 and len(pwd) >= 6:
with open(‘wj_users‘, mode=‘a‘, encoding=‘utf-8‘) as txt_users:
txt_users.write(‘{},{}\n‘.format(name, pwd))
print(‘恭喜您注册成功‘)
else:
print(‘用户名/密码不符合规范,请重新注册‘)
def get_users(file):
dict_user = {}
with open(file, mode=‘r‘, encoding=‘utf-8‘) as txt_users:
for line in txt_users:
dict_user[line[:line.find(‘,‘)]] = line[line.find(‘,‘) + 1:].strip()
return dict_user
def login(dict_user):
time = 3
while time > 0:
input_name = input(‘请输入您的用户名:‘)
input_pwd = input(‘请输入您的密码:‘)
time -= 1
if input_name in dict_user.keys() and input_pwd == dict_user[input_name]:
print(‘恭喜您登录成功‘)
break
else:
if time <= 0:
print(‘用户名/密码错误,您没有登录机会,强制退出成功‘)
else:
print(‘用户名/密码错误,请重试‘)
print(‘以下进入注册流程‘.center(50, ‘=‘))
register()
users = get_users(‘wj_users‘)
print(‘以下进入登录流程‘.center(50,‘=‘))
login(users)
原文:https://www.cnblogs.com/txbbkk/p/9410769.html