老男孩python学习第九天作业

练习一:写函数,验证用户名是否在文件data.txt中存在,如果存在返回 True,否则返回False

答:

# 构造数据
with open('data.txt', mode='w', encoding='utf-8') as f:
    f.write('1|alex|123123\n')
    f.write('2|eric|rwerwe\n')
    f.write('3|wupeiqi|ppp\n')

# 函数定义
def name_judge(name):
    data_list = []
    flag = False
    with open('data.txt', mode='r', encoding='utf-8') as f:
        for item in f:
            s, n, p = item.strip().split('|')
            data_dict = {'serial': s, 'name': n, 'pwd': p}
            data_list.append(data_dict)

    for i in data_list:
        if name == i['name']:
            flag = True
    return flag

# 函数调用
while True:
    char = input('请输入:')
    result = name_judge(char)
    print(result)

练习二:写函数,在函数内部生成如下规则的列表[1,1,2,3,5,8,13,21,34,55,....] (斐波那契数列),并返回。

要求:函数可接收一个参数,用于指定列表中元素最大不可以超过范围

答:

# 函数定义 
def fuc(num):
    result = []
    while True:
        if len(result) == 0:
            result.append(1)
        elif len(result) == 1:
            result.append(1)
        else:
            val = result[-1] + result[-2]
            if val > num:
                break
            result.append(val)
    return result

# 函数调用
v = fuc(100)
print(v)

练习三:写函数,返回两个数字中大的那个

答:

func = lambda n1, n2: n1 if n1 > n2 else n2

v = func(1, 2)
print(v)

练习四:看代码,写结果

USER_LIST = []
func = lambda x: USER_LIST.append(x)

v = func('alex')
print(v)
print(USER_LIST)

答:

print(v):None

print(USER_LIST):['alex']

练习五:写函数,实现数据分页

要求:

1.每页显示10条数据

2.让用户输入要查看的页码

答:

# 构建数据
USER_LIST = []
for i in range(1, 836):
    temp = {'name': '张三-%s' % i, 'email': '123%s@qq.com' % i}
    USER_LIST.append(temp)

# 数据总量
total_count = len(USER_LIST)
# 每页展示数量
per_page_count = 20
# 计算最大页码数
max_page_num, v = divmod(total_count, per_page_count)
if v != 0:
    max_page_num += 1

# 分页程序:利用列表切片功能实现
while True:
    page_num = input('请输入要查看的页码:')
    if int(page_num) in range(1, max_page_num + 1):
        start_index = (int(page_num) - 1) * per_page_count
        end_index = int(page_num) * per_page_count
        data = USER_LIST[start_index:end_index]
        for item in data:
            print(item)
    else:
        print('页码不合法,可查看范围[%s - %s]' % (1, max_page_num))
        continue

练习六:进制转换

情景一:二进制转十进制

v = '0b1001'
result = int(v, base=2)
print(result)

情景二:八进制转十进制

v = '0o1001'
result = int(v, base=8)
print(result)

情景三:十六进制转十进制

v = '0x1001'
result = int(v, base=16)
print(result)

情景四:十进制转二进制

v = 123
result = bin(v)
print(result)

情景五:十进制转八进制

v = 123
result = oct(v)
print(result)

情景六:十进制转十六进制

v = 123
result = hex(v)
print(result)

练习七:写函数,实现IP转换

情景一:

要求:将ip='192.168.12.79'中的每个十进制数转换成二进制并通过','连接起来生成一个新的字符串

答:

ip_bin_list = []
ip = '192.168.12.79'
ip_list = ip.split('.')
for i in ip_list:
    ip_bin_list.append(bin(int(i)))
ip_new = ','.join(ip_bin_list)
print(ip_new)

情景二:

要求:将ip='192.168.12.79'中的每个十进制数转换成二进制,并将转换后的二进制数字拼接转换成一个十进制数字

答:

ip_bin_list = []
ip_bin_new_list = []
ip = '192.168.12.79'
ip_list = ip.split('.')
for i in ip_list:
    ip_bin_list.append(bin(int(i))[2:])
for item in ip_bin_list:
    if len(item) < 8:
        item = (8 - len(item)) * '0' + item
    ip_bin_new_list.append(item)
ip_new = '0b' + ''.join(ip_bin_new_list)
ip_new_int = int(ip_new, base=2)
print(ip_new_int)

练习八:函数中高级

情景一:

name = 'alex'
def base():
    print(name)

def func():
    name = 'eric'
    base()

func()

答:

打印结果:alex

情景二:

name = 'alex'
def func():
	name = 'eric'
	def base():
    	print(name)
    base()
    
func()

答:

打印结果:eric

情景三:

name = 'alex'
def func():
	name = 'eric'
	def base():
    	print(name)
    return base
    
base = func()
base()

答:

打印结果:eric

情景四:

info = []

def func():
	print(item)

for item in range(10):
	info.append(func)
    
info[0]()

答:

打印结果:9

情景五:

info = []

def func(i):
    def inner():
        print(i)
	return inner

for item in range(10):
	info.append(func(item))
    
info[0]()
info[1]()
info[4]()

答:

打印结果:

0

1

4

练习九:生成随机验证码

答:

import random

# 函数定义
def get_random_code(length=6, alpha=True):
    data = []
    for i in range(length):
        v = chr(random.randint(48, 57))
        if alpha:
            upper_v = chr(random.randint(65, 90))
            lower_v = chr(random.randint(97, 122))
            v = random.choice([v, upper_v, lower_v])
        data.append(v)
    return ''.join(data)

# 函数调用
code = get_random_code()
print(code)

练习十:高级函数

场景一:将列表中每个元素都加100

答:

v1 = [11, 22, 33, 44]

result = map(lambda x: x + 100, v1)
print(list(result))

场景二:将两个列表中相同索引位置的数相加并返回

答:

v1 = [11, 22, 33, 44]
v2 = [55, 66, 77, 88]

result = map(lambda x, y: x + y, v1, v2)
print(list(result))

场景三:将列表中非数字类型元素剔除

答:

v1 = [11, 22, 33, 'asd', 44, 'def']

# 方法一:
result = filter(lambda x: type(x) == int, v1)
print(list(result))

# 方法二:
result = filter(lambda x: True if type(x) == int else False, v1)
print(list(result))

场景四:求列表中所有数字之和

答:

from functools import reduce

v1 = [11, 22, 33, 44]

result = reduce(lambda x, y: x + y, v1)
print(result)

练习十一:MD5加密

答:

import hashlib

def get_md5(data):
    obj = hashlib.md5('asdasasdas'.encode('utf-8'))
    obj.update(data.encode('utf-8'))
    result = obj.hexdigest()
    return result

val = get_md5('123')
print(val)

posted on 2019-11-01 17:10  傲慢小羽  阅读(290)  评论(1编辑  收藏  举报

导航