Python基础第七天
一、内容
二、练习
练习1
题目:编写函数,函数执行的时间是随机的
图示:

代码:
import time
import random
def func():
s = 1
l = []
for i in range(1,random.randrange(1,50)):
s *= i # s的最大值为:s = 1 * 2 * 3...50
time.sleep(0.05)
l.append(i) # 再把变量i添加至列表l里,此时l列表中的元素最大值为l = [1,2,3,4..50]
print("%s‘sproduct is%d"%(l,s))
func()
练习2
题目:编写装饰器,为函数加上统计时间的功能
代码:
import time
import random
def timmer(data):
def wrapper(*args,**kwargs):
start_time = time.time()
data(*args,**kwargs)
stop_time = time.time()
print('The function runs %s seconds'%(stop_time - start_time))
return wrapper
@timmer
def func():
s = 1
l = []
for i in range(1,random.randrange(1,50)):
s *= i # s的最大值为:s = 1 * 2 ...* 50
time.sleep(0.05)
l.append(i) # 再把变量i添加至列表l里,此时l列表中的元素最大值为l = [1,2,3...50]
print("%s‘sproduct is:%d"%(l,s))
func()
输出结果:
例:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]‘sproduct is20397882081197443358640281739902897356800000000
The function runs 2.407280206680298 seconds
练习3
题目:编写装饰器,为函数加上认证的功能
代码:
def auth(data):
def wrapper(*args,**kwargs):
user = 'knight'
pwd = 'dk123'
count = 1
while True:
if count == 4:
print('Too many times')
break
username = input('Please enter username:').strip()
passowrd = input('Please enter password:')
if username == user and passowrd == pwd:
print('Login successfully!')
data(*args, **kwargs)
break
else:
print('Login failed')
print('You still have %s chances'%(3-count))
count += 1
return wrapper
@auth
def func():
s = 1
l = []
for i in range(1,random.randrange(1,50)):
s *= i # s的最大值为:s = 1 * 2 ...* 50
time.sleep(0.05)
l.append(i) # 再把变量i添加至列表l里,此时l列表中的元素最大值为l = [1,2,3...50]
print("%s‘sproduct is:%d"%(l,s))
func()
练习4
题目:
编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"knight","password":"dk123"}')转成字典格式
文件内容如下:
{'name': 'knight', 'password': 'dk123'}
{'name': 'lisa', 'password': '123'}
{'name': 'tangbao', 'password': 'tangbao123'}
{'name': 'zhuozi', 'password': 'zz123'}
{'name': 'laozhang', 'password': 'lz110'}
图示:

代码:
# 编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
# 注意:从文件中读出字符串形式的字典,可以用eval('{"name":"knight","password":"dk123"}')转成字典格式
db_path=r'C:\Users\William\PycharmProjects\Item_Python1\day7\user_info.txt'
user_dic={
'knight':'dk123',
'lisa':'123',
'tangbao':'tangbao123',
'zhuozi':'zz123',
'laozhang':'lz110'
}
# 将字典强转为字符串写入至文件db_path中
with open(db_path,'w',encoding='utf-8') as f:
f.write(str(user_dic))
# 定义一个字典,让用户名默认对应None,登陆状态默认对应False
login_dic={
'user':None,
'status':False,
}
# 装饰器函数
def auth(func):
def wrapper(*args,**kwargs):
with open(db_path,'r',encoding='utf-8') as f:
user_dic=eval(f.read()) # 将文件"db_path"里的内容转成字典形式
# 用户名不为空,并且登陆状态不是False
while not login_dic['user'] and not login_dic['status']:
username = input('Please enter username:').strip()
password = input('Please enter password:')
if username in user_dic: # 判断用户名是否在字典user_dic内,当在字典user_dic中时
if password == user_dic[username]: # 判断密码是否为字典user_dic中键所对应的值。
print('login successful')
login_dic['user'] = username # 将用户输入的用户名添加至login_dic字典里
login_dic['status'] = True # 将login_dic中的’status‘的False改为True
# (登陆状态改为True)
res=func(*args,**kwargs)
return res
else:
print('password error') # 密码若不匹配字典user_dic[username]中时,提示密码错误
continue # 并退出本次循环继续循环(反复输入)
else:print('not found username') # 如果不在字典user_dic里时提示没有找到用户名
# 表示用户为为空时并且登陆状态为False时,直接输出原函数
else:
res = func(*args, **kwargs)
return res
return wrapper
@auth
# 原函数index
def index():
print('welcome to index')
# 原函数home
@auth
def home(name):
print('welcome %s to home page'%name)
# 调用函数index与home
index()
home('knight')
输出结果:
1、输入一个不存在于字典user_dic中的用户名:

2、输入一个存在于字典user_dic中的用户名,但密码不匹配:

3、输入一个存在于字典user_dic中的,并且密码匹配:

练习5
题目:编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果
代码:
from urllib.request import urlopen
def get(url):
return urlopen(url).read() # 将下载的内容直接返回
print(get('https://www.python.org'))
练习6
题目:为练习5编写装饰器,实现缓存网页内容的功能:
具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中
图示:

代码:
from urllib.request import urlopen # 调用下载模块
import os
cache_path=r'C:\Users\William\PycharmProjects\Item_Python1\day7\cache.txt'
def make_cache(func):
def wrapper(*args,**kwargs):
if os.path.getsize(cache_path):
# 返回文件大小,如果文件不存在就返回错误,这里表示有缓存
print('\033[45m*******有缓存*******\033[0m') # 打印有缓存,\033[45m...\033[0m 表示字体颜色
with open(cache_path,'rb') as f: # 将这个文件以"rb"的模式读取出来,二进制的方式读
res = f.read() # 得到二进制
else:
# 文件没有内容,直接返回原函数,这里表示无缓存
res=func(*args,**kwargs)
with open(cache_path,'wb') as f: # 将原函数的内容以二进制的写的方式直接写入至文件cache_path中
f.write(res)
return res
return wrapper
@make_cache
# 原函数
def get(url):
return urlopen(url).read()
# 调用函数
print('========>first')
print(get('https://www.python.org'))
print('========>second')
print(get('https://www.python.org'))
print('========>third')
print(get('https://www.python.org'))
练习7
题目:基于上面网页缓存装饰器的基础上,实现缓存不同网页的功能,要求,用户提交的不同url,都能缓存下来,对相同的url发起下载请求,优先从缓存里取内容。
图示:
示例:

浙公网安备 33010602011771号