1.写函数,计算传入数字参数的和。(动态传参)
def sum_count(*args): return sum(args) print(sum_count(2,3,4,5))2.写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作
import os def modify(name,old_str,new_str): new_name = name + ".new" with open(name,'r+',encoding = "utf-8") as f: for line in f: if old_str in line: line = line.replace(old_str,new_str) with open(new_name, "w", encoding="utf-8") as f_new: f_new.write(line) os.rename(new_name,name) modify("eval.text","rain","sunny")3.写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容
def space(args): result = "无空格" for i in args: if i.isspace(): result = "有空格" # break return result a = space("12335") print(a)4.写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容(对value的值进行截断),并将新内容返回给调用者,注意传入的数据可以是字符、list、dict
def inspect(dic): for k,v in dic.items(): if len(v) > 2: dic[k] = v[:2] return dic dic = {"k1": "v1v1", "k2": [11,22,33,44]} print(inspect(dic))5.写函数,返回一个扑克牌列表,里面有52项,每一项是一个元组
def poke(): list = ["红心","草花","黑桃A","梅花"] num = [i for i in range(2,11)] num.extend("JQGA") return [(x,y) for x in list for y in num] print(f"一共有{len(poke())}张牌,他们是{poke()}")6.写函数,传入n个数,返回字典{‘max’:最大值,’min’:最小值}
def ext(*args): max_num = max(*args) min_num = min(*args) return {"max":max_num,"min":min_num} val = ext(2,5,7,8,4,15,188) print(val)7.写函数,专门计算图形的面积
def area(): def rec(x,y): print(f"面积为:{x * y}") def square(x): print(f"面积为:{x * x}") def circle(x): print(f"面积为:{3.14 * x * x}") while True: name = input("输入图形:").strip() if name == "长方形": x = float(input("输入长:").strip()) y = float(input("输入宽:").strip()) return rec(x,y) elif name == "正方形": x = float(input("输入边长:").strip()) return square(x) elif name == "圆形": x = float(input("输入半径:").strip()) return circle(x) area()8.写函数,传入一个参数n,返回n的阶乘
def fac(n): res = 1 for i in range(1, n + 1): res = res * i return res print(fac(7))9.编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
account_status = False def login(func): dict = {} def inner(*args,**kwargs): global account_status if not account_status: with open("account.txt","r",encoding="utf-8") as f: for line in f: line = line.strip().split(",") dict[line[0]] = line[1] print(dict) username = input("username:") password = input("password:") if dict.__contains__(username) and dict[username] == password: print("登陆中") account_status = True func(*args,**kwargs) else: print("账户名或密码错误") else: print("已经认证通过") func(*args,**kwargs) return inner @login def movie(): print("watch movie") @login def music(vip_level): if vip_level > 3: print("high level") else: print("listen to music") movie() music(4)10.# 解释闭包的概念 1闭包:即函数定义和函数表达式位于另一个函数的函数体内(嵌套函数)。 2这些内部函数可以访问它们所在的外部函数中声明的所有局部变量、参数。 3当其中一个这样的内部函数在包含它们的外部函数之外被调用时,就会形成闭包。 4也就是说,内部函数会在外部函数返回后被执行。而当这个内部函数执行时,它仍然必需访问其外部函数的局部变量、参数以及其他内部函数。 5这些局部变量、参数和函数声明(最初时)的值是外部函数返回时的值,但也会受到内部函数的影响 11.生成器有几种方式获取value? for循环,next()方法 12.用map来处理字符串列表,把列表中所有人都变成sb,比方alex_sb
name=['alex','wupeiqi','yuanhao','nezha'] new_name = list(map(lambda i:i + "_sb",name)) print(new_name)13.用filter函数处理数字列表,将列表中所有的偶数筛选出来
num = [1,3,5,6,7,8] new_num = list(filter(lambda i:i % 2 == 0,num)) print(new_num)14.如下,每个小字典的name对应股票名字,shares对应多少股,price对应股票的价格 portfolio = [ {‘name’: ‘IBM’, ‘shares’: 100, ‘price’: 91.1}, {‘name’: ‘AAPL’, ‘shares’: 50, ‘price’: 543.22}, {‘name’: ‘FB’, ‘shares’: 200, ‘price’: 21.09}, {‘name’: ‘HPQ’, ‘shares’: 35, ‘price’: 31.75}, {‘name’: ‘YHOO’, ‘shares’: 45, ‘price’: 16.35}, {‘name’: ‘ACME’, ‘shares’: 75, ‘price’: 115.65} ] 通过哪个内置函数可以计算购买每支股票的总价
data = map(lambda x:x['shares'] * x['price'],portfolio) for i in data: print(i)用filter过滤出,单价大于100的股票有哪些
data = filter(lambda x:x['price'] > 100,portfolio) for i in data: print(i)15.请将以字母“a”开头的元素的首字母改为大写字母
li = ['alex', 'egon', 'smith', 'pizza', 'alen'] list = [i.capitalize() if i.startswith("a") else i for i in li] print(list)16.请以列表中每个元素的第二个字母倒序排序
li = ['alex', 'egon', 'smith', 'pizza', 'alen'] re = sorted(filter(lambda x:x[1],li)) print(re)17.有名为poetry.txt的文件,其内容如下,请删除第三行
a = ( "昔人已乘黄鹤去,此地空余黄鹤楼。\n" "黄鹤一去不复返,白云千载空悠悠。\n" "晴川历历汉阳树,芳草萋萋鹦鹉洲。\n" "日暮乡关何处是?烟波江上使人愁。" ) # with open("popetry.txt","w",encoding="utf-8") as f: # f.write(a.strip()) def poem(): with open("popetry.txt","r",encoding="utf-8") as r: with open("popetry_new.txt","w",encoding="utf-8") as w: line = r.read().strip().split() line.pop(2) for i in line: w.write(i + "\n") poem()18.写一个程序,判断该文件中是否存在”alex”, 如果没有,则将字符串”alex”添加到该文件末尾,否则提示用户该用户已存在
a = ("pizza\n" "alex\n" "egon") with open("username.txt","w",encoding="utf-8") as f: f.write(a.strip()) def judge(): with open("username.txt","r+",encoding="utf-8") as f: line = f.read() s = "alex" if s in line: print("该用户已存在") else: f.write("alex") judge()19.有名为user_info.txt的文件,其内容格式如下,写一个程序,删除id为100003的行
a = """pizza,100001 alex,100002 egon,100003""" # with open("user_info.txt","w",encoding="utf-8") as f: # f.write(a) def discard(): with open("user_info.txt","r",encoding="utf-8") as f: with open("user_info_new.txt","w",encoding="utf-8") as f_new: line = f.read().strip().split() id = "100003" for i in line: if id in i: line.pop(line.index(i)) else: f_new.write(i + "\n") discard()20.有名为user_info.txt的文件,其内容格式如下,写一个程序,将id为100002的用户名修改为alex li
def change(): with open("user_info.txt","r",encoding="utf-8") as f: with open("user_info_new.txt","w",encoding="utf-8") as f_new: for line in f: # print(line) id = "100002" if id in line: val,id = line.split(",") val = "alex li" line = ",".join([val,id]) f_new.write(line) else: f_new.write(line) change()21.写一个计算每个程序执行时间的装饰器
import time def calc(fun): def inner(): start_time = time.time() fun() end_time = time.time() spend_time = end_time - start_time print(f"花费时间为:{spend_time}") return inner @calc def music(): time.sleep(3) print("listen to music") @calc def movie(): time.sleep(2) print("watch movies") movie() music()22.写一个摇骰子游戏,要求用户压大小,赔率一赔一。要求:三个骰子,每个骰子的值从1-6,摇大小,每次打印摇出来3个骰子的值
import random def gamble(): while True: num = [random.randint(1, 7) for i in range(3)] gamble_money = sum(num) print("游戏开始".center(20,"*")) choose = input("输入你的选择-1.大 2.小 3.退出:").strip() if choose == "3": print("退出游戏") break money = int(input("输入本金:").strip()) if choose == "1": use_money = int(input("压多少钱:").strip()) if gamble_money >= 9: money += use_money print(f"你赢了,赢了{use_money}元,你还剩{money}元") print(f"骰子结果是{gamble_money}") else: money -= use_money print(f"你输了,输了{use_money}元,你还剩{money}元") print(f"骰子结果是{gamble_money}") elif choose == "2": use_money = int(input("压多少钱:").strip()) if gamble_money < 9: money += use_money print(f"你赢了,赢了{use_money}元,你还剩{money}元") print(f"骰子结果是{gamble_money}") else: money -= use_money print(f"你输了,输了{use_money}元,你还剩{money}元") print(f"骰子结果是{gamble_money}") else: print("输入错误") gamble()23.lambda是什么?请说说你曾在什么场景下使用lambda?
#匿名函数 res = map(lambda x:x+2,[1,5,7,4,8]) for i in res:print(i)24.生成器和迭代器的区别? 生成器是一种特殊的迭代器,生成器自动实现了“迭代器协议”(即__iter__和next方法),不需要再手动实现两方法。 生成器在迭代的过程中可以改变当前迭代值,而修改普通迭代器的当前迭代值往往会发生异常,影响程序的执行。