#购物车 li = [ {'name':'苹果','price':10}, {'name':'香蕉','price':20}, {'name':'西瓜','price':30} ] #把货品放在货架上 money = '300' #钱 shoop_dic = {} #购物车 key:商品 value : 价钱 print("欢迎光临") for i,k in enumerate(li): print('序号{},商品{},价格{}'.format(i,k['name'],k['price'])) chose = input("请选择你的商品序号:") if int(chose) >= 0 and int(chose) <= len(li): num = input("你要购买的商品数量:") if num.isdigit(): if int(money) > li[int(chose)]['price'] * int(num): money = int(money) - li[int(chose)]['price'] * int(num) if li[int(chose)]['name'] in shoop_dic: shoop_dic[li[int(chose)]] = shoop_dic[li[int(chose)]] + int(num) else: shoop_dic[li[int(chose)]['name']] = int(num) print('购物车商品{},剩余钱{}'.format(li[int(chose)]['name'], money)) else: print("钱不够") else: print("序号错误")
#用户注册登录代码 a = input('1 注册,2 登陆:') def denglu(): username = input("请输入用户名:") passwd = input("请输入密码:") with open('user_list') as f2: for line in f2: user,pwd = line.split('|') if username == user and passwd == pwd: print("登录成功") else: print("登录失败") def zhuce(): username = input("请输入用户名:") passwd = input("请输入密码:") with open('user_list','w',encoding='utf-8') as f1: f1.write('{}|{}'.format(username,passwd)) print("注册成功") if a == '1': zhuce() elif a == '2': denglu() else: print("输入有误")
#编写装饰器,为多个函数加上认证功能
#要求登录成功一次,后续的函数都无需再输入用户名和密码
FLAG = False def login(func): def inner(*args,**kwargs): #装饰的内容 global FLAG if FLAG: ret = func(*args, **kwargs) return ret else: username = input("name:") passwd = input("passwd:") if username == 'xiao' and passwd == '123': print("成功") FLAG = True ret = func(*args,**kwargs) return ret else: print("登录失败") return inner @login def shoplist_add(): print("增加一件物品") @login def shoplist_del(): print("删除一件物品") shoplist_add() shoplist_del()
#生成器,从文件中读取内容,在没一次读取到的内容之前加上“###” 之后返回用户
def neirong(p): with open(p,encoding='utf-8') as f: while True: g = f.readline() yield g ff = neirong('file') print('****' + ff.__next__()) print('****' + ff.__next__()) print('****' + ff.__next__()) ----------------------------------------------------- def check_file(p): with open(p, encoding='utf-8') as f: for i in f: yield '***' +i for i in check_file('file'): print(i.strip())
#处理文件,用户指定查找的文件和内容,将文件中包含要查找的内容每一行输出到屏幕
def check_file(a,b): with open(a,encoding='utf-8') as f: for i in f.readline(): if b in i: yield i g = check_file('file','xiao') for i in g: print(i)
# 接收用户输入页码,每页5条,仅输出当页的内容
# with open('file',encoding='utf-8') as f: # l = f.readlines() # page_in = int(input('输入第几页:')) # pages,mod = divmod(len(l),5) # if mod != 0: # pages += 1 # # if page_in > pages or page_in <= 0: # print("输入有误") # elif page_in == pages and mod != 0: # for i in range(mod): # print(l[(page_in - 1) *5 +i].strip()) # else: # for i in range(5): # print(l[(page_in - 1) * 5 +i].strip())
# 3.用map来处理字符串列表,把列表中所有人都变成sb,比方alex_sb
name=['alex','wupeiqi','yuanhao','nezha'] # def f(p): # return (p +"_sb") # ret = map(f,name) # for i in ret: # print(i) # ret = map(lambda p: p + '_sb',name) # for i in ret: # print(i)
#4.用filter函数处理数字列表,将列表中所有的偶数筛选出来
# num = [1,3,5,6,7,8] # ret = filter(lambda p:p % 2 == 0,num) # for i in ret: # print(i)
# 5.随意写一个20行以上的文件
# 运行程序,先将内容读到内存中,用列表存储。
# 接收用户输入页码,每页5条,仅输出当页的内容
# with open('file',encoding='utf-8') as f: # l = f.readlines() # page_in = int(input('输入第几页:')) # pages,mod = divmod(len(l),5) # if mod != 0: # pages += 1 # # if page_in > pages or page_in <= 0: # print("输入有误") # elif page_in == pages and mod != 0: # for i in range(mod): # print(l[(page_in - 1) *5 +i].strip()) # else: # for i in range(5): # print(l[(page_in - 1) * 5 +i].strip())
# 6.如下,每个小字典的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} ] # 6.1.计算购买每支股票的总价 # def f(dic): # ret = {dic['name'] : round(dic['shares'] * dic['price'],2)} # return ret # # ret = map(f,portfolio) # for i in ret: # print(i) # 6.2.用filter过滤出,单价大于100的股票有哪些 # def f(dic): # if dic['price'] > 100: # ret = {dic['name']:dic['price']} # return ret # ret = filter(f,portfolio) # for i in ret: # print(i) # ret = filter(lambda dic:dic['price'] > 100,portfolio) # print(list(ret))
#员工信息查询
ret = 'select name,age where age > 20' ret = ret.split('where') con = ret[1] key1,val1 = con.split('>') ver = ret[0].split('select') username,userage = ver[1].split(',') name = username.strip() age = userage.strip() key = key1.strip() val = val1.strip() #打开文件 dic = {'name':1,'age':2,'haoma':3,'gongzuo':4} def openfile(p): with open(p,encoding='utf-8') as f: ret = f.readlines() return ret #分析 def fenxi(age,num): g = openfile('file1') for i in range(len(g)): ret = g[i].split() if int(ret[dic[age]]) > int(num): yield ret # # #展示 def zhanshi(name,age): d = fenxi(key,val) for i in d: name1 = i[dic[name]] age1 = i[dic[age]] yield name1,age1 g = zhanshi(name,age) for i in g: print(i)
#阶乘 10*9*8*7*6*5*4*3*2*1 def func(p): if p == 1: return 1 return p * func(p-1) ret = func(9) print(ret)
# 斐波那契 # 问第n个斐波那契数是多少 #1,1,2,3,5,8 def func(p): if p == 1 or p == 2: return 1 return func(p - 1) + func(p -2) # func(3) + 1 # func(2)+func(1) +1 # 1 + 1 +1 =3 ret = func(20) print(ret)
import re import json from urllib.request import urlopen def getPage(url): # 下载到一个url网站的信息 response = urlopen(url) return response.read().decode('utf-8') # 信息一般挡下来是字节的 ,将其转为utf-8编码 def parsePage(s): #匹配信息,反悔生成器 ,迭代自己想看的信息 com = re.compile( '<div class="item">.*?<div class="pic">.*?<em .*?>(?P<id>\d+).*?<span class="title">(?P<title>.*?)</span>' '.*?<span class="rating_num" .*?>(?P<rating_num>.*?)</span>.*?<span>(?P<comment_num>.*?)评价</span>', re.S) ret = com.finditer(s) for i in ret: yield { "id": i.group("id"), "title": i.group("title"), "rating_num": i.group("rating_num"), "comment_num": i.group("comment_num"), } def main(num): url = 'https://movie.douban.com/top250?start=%s&filter=' % num response_html = getPage(url) #读取url页面信息 ret = parsePage(response_html) #正则 表达式匹配 print(ret) f = open("move_info7", "a", encoding="utf8") #打开一个文件 for obj in ret: #把url读取的循环写入文件中 print(obj) data = str(obj) f.write(data + "\n") f.close() count = 0 for i in range(10): # 有10页 进行循环 main(count) count += 25 #一页 25个记录
import re def rep(exp): if '--' in exp: return exp.replace('--','+') elif '+-' in exp: return exp.replace('+-','-') else: return exp def ji_son(exp): #用来计算括号内表达式的乘除 if '/' in exp: a,b = exp.split('/') return str(float(a)/float(b)) elif '*' in exp: a,b = exp.split('*') return str(float(a)*float(b)) def no_kuohao(exp): exp_new = exp.strip('()') #给传来的(-40/5) 去括号 -40/5 while True: ret = re.search('\d+\.?\d*[*/]-?\d+\.?\d*',exp_new) if ret: ret1 = ret.group() #40/5 #print(ret1) ret1_ji = ji_son(ret1) #计算 8.0 #print(ret1_ji) zhi = exp_new.replace(ret1,ret1_ji) #-8.0 #print(zhi) exp_new = rep(zhi) else: ret = re.findall('-?\d+\.?\d*',exp_new) sum = 0 for i in ret: sum = float(sum) + float(i) return str(sum) def man(express): #主函数 new = express.replace(' ','') #去空格 while True: ret = re.search('\([^()]+\)',new) #取到一个括号 if ret: ret1 = ret.group() #print(ret1) #(-40/5) new_son = no_kuohao(ret1) #对括号内的表达式计算 ji = new.replace(ret1,new_son) #print(ji) new = rep(ji) else: print("没有括号",new) new_son1 = no_kuohao(new) return new_son1 express = " 1 - 2 * (( 60 -30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 *568/14))) - (-1*3)/(16-3*2)" func = man(express) print(func)