1.文件a.txt內容:每一行內容分別爲商品名字,價錢,個數。 apple 10 3 tesla 100000 1 mac 3000 2 lenovo 30000 3 chicken 10 3 經過代碼,將其構建成這種數據類型:[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 並計算出總價錢。
dic = {} lis = [] price = 0 with open('a.txt',encoding='utf-8') as f_read: for f in f_read.readlines(): content = f.split('\n') dic['name'] = content[0].split()[0] dic['price'] = content[0].split()[1] dic['amount'] = content[0].split()[2] price += int(dic['price']) * int(dic['amount']) lis.append(dic) print(lis) print(price)
2.有以下文件:
------------------------------------------------------------ alex是老男孩python發起人,建立人。 alex實際上是人妖。 誰說alex是sb? 大家真逗,alex再牛逼,也掩飾不住資深屌絲的氣質。 ------------------------------------------------------------ 將文件中全部的alex都替換成大寫的SB。
import os with open('d.txt',encoding='utf-8') as f_read, \ open('.d.txt.swap','w',encoding='utf-8') as f_write: f = f_read.read() f_write.write(f.replace('alex','SB')) os.remove('d.txt') os.rename('.d.txt.swap','d.txt')
3.文件a1.txt內容:每一行內容分別爲商品名字,價錢,個數。 文件內容: name:apple price:10 amount:3 year:2012 name:tesla price:100000 amount:1 year:2013 經過代碼,將其構建成這種數據類型: [{'name':'apple','price':10,'amount':3}, {'name':'tesla','price':1000000,'amount':1}......] 並計算出總價錢。
lis = [] dic = {} price = 0 with open('d.txt',encoding='utf-8') as f_read: for f in f_read.readlines(): content = f.split('\n')[0].split() for j in content: dic[j.split(':')[0]] = j.split(':')[1] price += int(dic['price']) * int(dic['amount']) lis.append(dic) print(lis) print(price)
4.文件內容: 序號 部門 人數 平均年齡 備註 1 python 30 26 單身狗 2 Linux 26 30 沒對象 3 運營部 20 24 女生多 經過代碼,將其構建成這種數據類型: [{'序號':'1','部門':Python,'人數':30,'平均年齡':26,'備註':'單身狗'}, ......]
lis = [] dic = {} key_list = [] value_list = [] with open('a.txt',encoding='utf-8') as f_read: f1 = f_read.readline().split('\n')[0].split(' ') for k in f1: if not len(k): continue key_list.append(k) for v in f_read.readlines(): v = v.split('\n')[0].split(' ') for r_v in v: if not len(r_v): continue value_list.append(r_v) for long in range(len(key_list)): dic[key_list[long]] = value_list[long] lis.append(dic) print(lis) ret = [] with open('a.txt',encoding='utf-8') as f1: li = f1.readline().split() for i in f1: dic = {} for j in range(len(li)): dic[li[j]] = i.split()[j] ret.append(dic) print(ret) lis = [] with open('a.txt',encoding='utf-8') as f2: keys = [i for i in f2.readline().split()] for value in f2: lis.append({k:v for k,v in zip(keys,value.split())}) print(lis)
5.寫函數,檢查獲取傳入列表或元組對象的全部奇數位索引對應的元素,並將其做爲新列表返回給調用者。
a = [1,2,3,4] def func1(args): l = [] for i in range(len(args)): if i % 2 == 1: l.append(args[i]) return l print(func1(a)) def func(args):return args[0::2] # 步長切片 print(func(a))
6.寫函數,判斷用戶傳入的對象(字符串、列表、元組)長度是否大於5。
a='asdasdasd' b=['asda','','asd'] c=(1,12) def func(args): if len(args) >= 5: return "大於或等於5" return "小於5" print(func(a)) print(func(b)) print(func(c)) def func(args): return "%s 大於或等於5" %str(args) if len(args) >= 5 else "%s 小於5" %str(args) print(func(a)) print(func(b)) print(func(c)) def func1(argv): return len(argv) > 5 # 直接返回bool值
7.寫函數,檢查傳入列表的長度,若是大於2,那麼僅保留前兩個長度的內容,並將新內容返回給調用者。
a = [1,2,3,4,5] def func(argv): if len(argv)>2: return argv[0:2] return argv def func(argv): return argv[:2] if len(argv) > 2 else argv def func(argv): return argv[0:2] print(func(a))
8.寫函數,計算傳入字符串中【數字】、【字母】、【空格] 以及 【其餘】的個數,並返回結果。
def func(argv): n = 0 s = 0 space = 0 o = 0 for i in argv: if i.isdigit(): n+=1 elif i.isalpha(): s += 1 elif i.isspace(): space += 1 else: o += 1 print('數字%s個,字符%s個,空格%s個,其它%s個' %(n,s,space,o)) func('as asd 123<> 123')
9.寫函數,檢查用戶傳入的對象(字符串、列表、元組)的每個元素是否含有空內容,並返回結果。
a =('1','',2) def func(argv): for i in argv: i = str(i) if i.isdigit(): print(i) continue elif i.isspace(): return argv,"有空值" return argv,'無空值' print(func(a))
10.寫函數,檢查傳入字典的每個value的長度,若是大於2,那麼僅保留前兩個長度的內容,並將新內容返回給調用者。 dic = {"k1": "v1v1", "k2": [11,22,33,44]} PS:字典中的value只能是字符串或列表
dic = {"k1": "v1v1", "k2": [11,22,33,44]} def func(argv): for k in argv: if len(argv[k]) > 2: argv[k] = argv[k][0:2] return argv print(func(dic)) def func(argv): for k in argv: argv[k] = argv[k][:2] return argv print(func(dic))
11.寫函數,接收兩個數字參數,返回比較大的那個數字。
def func(x,y): return x if x > y else y print(func(4,6))
12.寫函數,用戶傳入修改的文件名,與要修改的內容,執行函數,完成整個文件的批量修改操做.
import os def func(f,old,new): with open(f,encoding='utf-8') as f_r,\ open('.%s.bak' %f,'w',encoding='utf-8') as f_w: for i in f_r.readlines(): f_w.write(i.replace(old,new)) os.remove(f) os.rename('.%s.bak' %f,f) func('d.txt','alex','SB')
13.寫一個函數完成三次登錄功能,再寫一個函數完成註冊功能
def userfile(): username = input("請輸入用戶名:").strip() password = input("請輸入密碼:").strip() return username,password def register(): while True: info = userfile() username, password = info[0], info[1] with open('user.txt','r+',encoding='utf-8') as f: for i in f: li = i.strip().split() if username == li[0] or len(username) == 0 : print('用戶名已存在,請從新輸入') break else: f.write('\n%s %s' %(username,password)) break return "註冊成功" def login(): count = 0 while count < 3: count += 1 info = userfile() username, password = info[0], info[1] with open('user.txt',encoding='utf-8') as f: for i in f.readlines(): i = i.split('\n')[0] user,pwd = i.split(' ')[0],i.split(' ')[1] if username == user and password == pwd: return "%s登錄成功" %username else: continue return "登錄失敗" def func(): print('welcome to one world one dream') while True: choice = input('請輸入你要進行的操做1.登錄 2.註冊 3.退出').strip() if not len(choice):continue if int(choice) == 1: ret = login() print(ret) elif int(choice) == 2: ret = register() print(ret) continue else: print("bye") break func()
14.模擬公司hr錄入員工帳號密碼的程序。 1),員工的帳號密碼存儲在這種數據類型中: user_list = [ {'username':'barry','password':'1234'}, {'username':'alex','password':'asdf'}, ......... ] 2)非法字符模板:board = ['張三','李小四','王二麻子'] 3)Hr輸入用戶名,密碼(可持續輸入,若是想終止程序,那就在輸入用戶名時輸入Q或者q退出程序), 在Hr輸入用戶名時,檢測此用戶名是否有board裏面的非法字符,若是有非法字符, 則將非法字符替換成同數量的*(如王二麻子替換成****),而後添加到user_list中, 若是沒有非法字符,則直接添加到user_list中,每次添加成功後,打印出剛添加的用戶名,密碼。
user_list = [ {'username':'barry','password':'1234'}, {'username':'alex','password':'asdf'}] board = ['張三','李小四','王二麻子'] while True: username = input('請輸入用戶名:').strip() if not username:continue if username.upper() == 'Q':break if username in board: username = username.replace(username,'*'*len(username)) password = input('請輸入密碼:').strip() dic = {} dic['username'] = username dic['password'] = password user_list.append(dic) print(dic) print(user_list)
15.按要求完成下列轉化(不要按照索引去作)。 list3 = [ {"name": "alex", "hobby": "抽菸"}, {"name": "alex", "hobby": "喝酒"}, {"name": "alex", "hobby": "燙頭"}, {"name": "alex", "hobby": "Massage"}, {"name": "wusir", "hobby": "喊麥"}, {"name": "wusir", "hobby": "街舞"}, ] 如何把上面的列表轉換成下方的列表? list4 = [ {"name": "alex", "hobby_list": ["抽菸", "喝酒", "燙頭", "Massage"]}, {"name": "wusir", "hobby_list": ["喊麥", "街舞"]}, ]
dic3 = {} dic4 = {} list4 = [] for i in list3: dic3.setdefault('name') dic4.setdefault('name') dic3.setdefault('hobby',[]) dic4.setdefault('hobby',[]) if i['name'] == 'alex': dic3['name'] = 'alex' dic3['hobby'].append(i['hobby']) else: dic4['name'] = 'wusir' dic4['hobby'].append(i['hobby']) list4.append(dic3) list4.append(dic4) print(list4)
16.實現一個整數加法計算器: 如:content = input(‘請輸入內容:’) # 如用戶輸入:5+8+7....(最少輸入兩個數相加), 而後進行分割再進行計算,將最後的計算結果添加到此字典中(替換None): dic={‘最終計算結果’:None}。
dic = {} sum = 0 content = input('>>').strip() content = content.split('+') for i in content: i = int(i) sum += i dic['最終計算結果']=sum print(dic)
17.查找列表li中的元素,移除每一個元素的空格,並找出以’A’或者’a’開頭,並以’c’結尾的全部元素,並添加到一個新列表中,最後循環打印這個新列表
li = ['taibai ','alexC','AbC ','egon',' Ritian',' Wusir',' aqc'] n_l = [] for i in li: i = i.strip() # if (i.startswith('a') or i.startswith('A')) and i.endswith('c'): if i.upper().startswith('A') and i.endswith('c'): n_l.append(i) print(n_l)
18.補充代碼(從已有的代碼下面繼續寫): 有以下值li= [11,22,33,44,55,77,88,99,90],將全部大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中。
li = [11,22,33,44,55,77,88,99,90] result = {} for row in li: result.setdefault('k1',[]) result.setdefault('k2',[]) if row > 66: result['k1'].append(row) else: result['k2'].append(row) print(result)
19.計算用戶輸入內容中索引爲奇數而且對應的元素爲數字的個數(沒有則個數爲零)
count = 0 content = input('>>').strip() for k,v in enumerate(content): print(k,v,type(v),v.isdigit()) if k % 2 == 1 and v.isdigit(): count += 1 print(count) a = '2' print(a.isdigit())
20.分別使用while循環,和for循環打印1-2+3-4+5.......+99的結果
sum = 0 n=1 while n < 100: if n % 2 == 0: sum -= n else: sum += n n += 1 print(sum) sum = 0 for i in range(100): if i % 2 == 0: sum -= i else: sum += i print(sum) for i in range(100,-1,-1): print(i)
21.有列表li = [‘alex’,’wusir’,’rain’],經過操做該列表構造一個字符串s=’alexwusirrain
li = ['alex','wusir','rain'] s= li[0]+li[1]+li[2] print(s) s1 = '*'.join(li) print(s1) print(s.split('l',1))
22.寫函數,返回一個撲克牌列表,裏面有52項,每一項是一個元組 例如:[(‘紅心’,2), (‘草花’,2), …(‘黑桃,‘A’)]
def puke(): num = [] for n in range(2,11): num.append(n) num.extend(['J','Q','K','A']) lis = [] base = ['紅心','草花','黑桃','方塊'] for item in base: for m in num: lis.append((item,m)) return lis print(puke())
23.寫函數,傳入n個數,返回字典{‘max’:最大值,’min’:最小值} 例如:min_max(2,5,7,8,4) 返回:{‘max’:8,’min’:2}
def min_max(*args): l = [] dic ={} for i in args: l.append(i) l.sort() dic['max'] = l[-1] dic['min'] = l[0] return dic print(min_max(2,5,7,8,4)) def min_max(*args): the_max = args[0] the_min = args[0] for i in args: if i > the_max: the_max = i elif i < the_min: the_min = i return {'max':the_max,'min':the_min} print(min_max(2,5,7,8,4))
24.寫函數,專門計算圖形的面積 其中嵌套函數,計算圓的面積,正方形的面積和長方形的面積 調用函數area(‘圓形’,圓半徑) 返回圓的面積 調用函數area(‘正方形’,邊長) 返回正方形的面積 調用函數area(‘長方形’,長,寬) 返回長方形的面積
import math def area(name,*args): def round(x): return math.pi * x ** 2 def square(x): return x ** 2 def rectangle(x,y): return x * y if name == '圓形': return round(*args) elif name == '正方形': return square(*args) elif name == '長方形': return rectangle(*args) print(area('圓形',3)) print(area('正方形',3)) print(area('長方形',2,3))
25.寫函數,傳入一個參數n,返回n的階乘。例如: cal(7) 計算7 * 6 * 5 * 4 * 3 * 2 * 1
def cal(n): sum = 1 print(sum) for i in range(n,1,-1): sum = sum * i return sum print(cal(6)) sum = 1 def cal(n): global sum if n >= 1: sum = n * cal(n-1) return sum print(cal(6))
26.編寫下載網頁內容的函數,要求功能是:用戶傳入一個url,函數返回下載頁面的結果
from urllib import request def func(url): with request.urlopen(url) as f: data = f.read() print('status',f.status,f.reason) for k,v in f.getheaders(): print('%s:%s' %(k,v)) print('Data:',data.decode('utf-8')) func('https://www.baidu.com') import requests def my_down(url = 'https://www.baidu.com'): return requests.get(url).content def get(): return requests.get(url).content return get print(my_down())
27.實現下載的頁面存放於文件中,若是文件內有值(文件大小不爲0),就優先從文件中讀取網頁內容,不然,就去下載,而後存到文件中 擴展功能:用戶能夠選擇緩存介質/緩存引擎,針對不一樣的url,緩存到不一樣的文件中
import requests import os def make_cache(func): def inner(*args,**kwargs): if not os.path.exists('cache.txt'): with open('cache.txt','w'): pass if os.path.getsize('cache.txt'): print(os.path.getsize('cache.txt')) with open('cache.txt',encoding='utf-8') as f_read: res = f_read.read() else: print('err') print(os.path.getsize('cache.txt')) res = func(*args,**kwargs) with open('cache.txt','w',encoding='utf-8') as f_write: f_write.write(res.decode('utf-8')) return res return inner @make_cache def get(url): return requests.get(url).content print(get('https://www.baidu.com'))
28.給每一個函數寫一個記錄日誌的功能, 功能要求:每一次調用函數以前,要將函數名稱,時間節點記錄到log的日誌中。 所需模塊: import time struct_time = time.localtime() print(time.strftime("%Y-%m-%d %H:%M:%S",struct_time))
import time,os def timmer(func): struct_time = time.localtime() def inner(*args): if not os.path.exists('log.txt'): with open('log.txt','w') : pass current_time = time.strftime('%Y-%m-%d %H:%M:%S',struct_time) with open('log.txt','a',encoding='utf-8') as f: f.write("\n%s\t%s"%(current_time,func.__name__)) func() return inner @timmer def test(): print('hello world')
29.編寫裝飾器,爲多個函數加上認證的功能(用戶的帳號密碼來源於文件),要求登陸成功一次,後續的函數都無需再輸入用戶名和密碼
dic = { 'status' : False } flag = False def auth(func): def inner(*args,**kwargs): user = [] global flag while not flag: user_info = login() with open('user.txt','r+',encoding='utf-8') as f: for i in f: i = i.strip().split() user.append(i[0]) if i[0] == user_info[0] and i[1] == user_info[1]: print('%s login success' %user_info[0]) flag = True if user_info[0] not in user: f.seek(0,2) f.write('\n%s\t%s' %(user_info[0],user_info[1])) flag = True while flag: ret = func(*args,**kwargs) return ret dic['status'] = True return inner def login(): username = input('請輸入用戶名:').strip() password = input('請輸入密碼').strip() return username,password @auth def func(): if dic['status']: print(' hello world ') @auth def func1(): if dic['status']: print(' hello elk ') func() func1()
30.在編寫裝飾器,爲多個函數加上認證的功能(用戶的帳號密碼來源於文件),要求登陸成功一次,後續的函數都無需再輸入用戶名和密碼。這個做業之上進行升級操做: 設置兩套密碼,一套爲京東帳號密碼,一套爲淘寶帳號密碼保存在文件中。 設置四個函數,分別表明 京東首頁,京東超市,淘寶首頁,淘寶超市。 循環打印四個選項:東首頁,京東超市,淘寶首頁,淘寶超市。 供用戶選擇,用戶輸入選項後,執行該函數,四個函數都加上認證功能,只要登錄成功一次,在選擇其餘函數,後續都無需輸入用戶名和密碼。 相關提示:用帶參數的裝飾器。裝飾器內部加入判斷,驗證不一樣的帳戶密碼。
import os dic = { 'name': None, 'status' : False } def auth(func): def inner(*args,**kwargs): if not dic['status']: username = input('請輸入用戶名:').strip() password = input('請輸入密碼:').strip() if not os.path.exists('user.txt'): with open('user.txt','w'):pass with open('user.txt',encoding='utf-8') as f: for i in f: i = i.strip().split() if username == i[0] and password == i[1]: ret = func(*args,**kwargs) dic['name'] = username dic['status'] = True return ret else: ret = func(*args,**kwargs) return ret return inner @auth def func1(): print('京東首頁') @auth def func2(): print('京東商城') @auth def func3(): print('淘寶首頁') @auth def func4(): print('淘寶商城') while True: func1() func2() func3() func4()
31.寫程序完成下列功能: 1),啓動程序,首頁面應該顯示成以下格式: 歡迎來到博客園首頁 1:請登陸 2:請註冊 3:文章頁面 4:日記頁面 5:評論頁面 6:收藏頁面 7:註銷 8:退出程序 2),用戶輸入選項,3~6選項必須在用戶登陸成功以後,才能訪問成功。 3),用戶選擇登陸,用戶名密碼從register文件中讀取驗證,三次機會,沒成功則結束整個程 序運行,成功以後,能夠選擇訪問3~6項,訪問頁面以前, 必需要在log文件中打印日誌, 日誌格式爲-->用戶:xx 在xx年xx月xx日 執行了 %s函數,訪問頁面時,頁面內容爲:歡 迎xx用戶訪問評論(文章,日記,收藏)頁面 4),若是用戶沒有註冊,則能夠選擇註冊,註冊成功以後,能夠自動完成登陸,而後進入首頁選擇。 5),註銷用戶是指註銷用戶的登陸狀態,使其在訪問任何頁面時,必須從新登陸。 6),退出程序爲結束整個程序運行。
import os import time flag = False dic = { 'username' : None, 'status' : False } def auth(func): def inner(*args,**kwargs): if not os.path.exists('log.txt'): with open('log.txt', 'w', encoding='utf-8'): pass if dic['status']: with open('log.txt', 'a', encoding='utf-8') as f3: f3.write('用戶%s 在%s 執行了%s函數 \n' % (dic['username'],time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()), func.__name__)) ret = func(*args,**kwargs) return ret else: i = 0 while i <= 3: username = input('請輸入你的用戶名:').strip() password = input('請輸入你的密碼:').strip() with open('user.txt',encoding='utf-8') as f1: for f in f1: f = f.strip().split() if f[0] == username and f[1] == password: dic['username'] = username dic['status'] = True ret = func(*args,**kwargs) with open('log.txt', 'a', encoding='utf-8') as f3: f3.write('用戶:%s 時間:%s exec:%s\n' % (dic['username'], time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()), func.__name__)) return ret else: i += 1 print('用戶名或者密碼錯誤,剩餘輸入次數%s' %(3-i)) continue return inner @auth def login(): print('%s登陸成功'%dic['username']) def register(): if not os.path.exists('user.txt'): with open('user.txt',encoding='utf-8'):pass global flag while not flag: username = input('請輸入須要註冊的用戶名:').strip() user_list = [] with open('user.txt','r',encoding='utf-8') as f2: for f in f2: f = f.strip().split() user_list.append(f[0]) if username in user_list: print('該用戶已存在,請換個用戶名') continue password = input('請輸入密碼:').strip() double_password = input('請再次輸入密碼:').strip() if password != double_password: print('密碼不匹配,請再次輸入') continue with open('user.txt','a',encoding='utf-8') as f3: f3.write('\n%s\t%s' %(username,password)) break print('%s註冊成功' %username) dic['username'] = username dic['status'] = True @auth def article(): print('歡迎訪問文章頁面!') @auth def diary(): print('歡迎訪問操做日誌頁面!') with open('log.txt',encoding='utf-8') as f4: for f in f4: print(f) @auth def comment(): print('歡迎訪問評論頁面!') @auth def collection(): print('歡迎訪問收藏頁面!') def log_out(): print('%s註銷成功!'%dic['username']) dic['username'] = None dic['status'] = False def web_exit(): global flag flag = True print('程序運行結束!') def display_list(): print('歡迎來到博客園首頁') lis = ['請登陸','請註冊','文章頁面','日誌頁面','評論頁面','收藏頁面','註銷','退出程序'] for l in lis: print(lis.index(l)+1,':',l) return len(lis) def web_index(): global flag while not flag: num_max = display_list() choice = input('請輸入要進行的操做:').strip() if not choice.isdigit(): continue choice = int(choice) if choice == 0 or choice > num_max: print('輸入不合法,請再次輸入!') if choice == 1: login() elif choice == 2: register() elif choice == 3: article() elif choice == 4: diary() elif choice == 5: comment() elif choice == 6: collection() elif choice == 7: log_out() elif choice == 8: web_exit() if __name__ == '__main__': web_index()