python3學習案例

""" 請打印出 1024 * 768 = *** """ shu = 1024 * 768 print("1024 * 768 = %d" %shu) """ 請打印出以下變量的值: # -*- coding: utf-8 -*- n = 123 f = 456.789 s1 = 'Hello, world' s2 = 'Hello, \'Adam\'' s3 = r'Hello, "Bart"' s4 = r'''Hello, Lisa!''' """ n = 123 f = 456789 / 1000 s1 = "'Hello, World'" s2 = "'Hello, \\'Adam\\''" s3 = "r'Hello, \"Bart\"'" s4 = 'r''\'\'\'Hello,\nLisa!\'\'\'' print('n=', n, '\nf=', f, '\ns1=', s1, '\ns2=', s2, '\ns3=', s3, '\ns4=', s4) """ ×××的成績從去年的72分提升到了今年的85分,請計算×××成績提升的百分點,並用字符串格式化顯示出'xx.x%',只保留小數點後1位: """ zuo_nain = 72 / 100 jin_nain = 85 / 100 r = (jin_nain - zuo_nain) * 100 print("提升%.1f%%" %r ) """ 請用索引取出下面list的指定元素: # -*- coding: utf-8 -*- L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa'] ] # 打印Apple: print(?) # 打印Python: print(?) # 打印Lisa: print(?) """ L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa']] print(L[0][0]) print(L[1][1]) print(L[2][2]) """ ×××身高1.75,體重80.5kg。請根據BMI公式(體重除以身高的平方)幫×××計算他的BMI指數,並根據BMI指數: 低於18.5:過輕 18.5-25:正常 25-28:過重 28-32:肥胖 高於32:嚴重肥胖 用if-elif判斷並打印結果: """ s = input("高》:") height = float(s) a = input("重》:") weight = float(a) BMI = weight / height ** 2 if BMI < 18.5: print("過輕") elif BMI < 25: print("正常") elif BMI < 28: print("過重") elif BMI < 32: print("肥胖") elif BMI > 32: print("嚴重肥胖") """ 請利用循環依次對list中的每個名字打印出Hello, xxx!: L = ['Bart', 'Lisa', 'Adam'] """ L = ['Bart', 'Lisa', 'Adam'] for i in L: print("Hello, %s" % i) """ 實現將列表:['a','a','b','a','b','c']輸出爲字典:{'a':3,'b':2,'c':1} """ str_list = ['a', 'a', 'b', 'a', 'b', 'c'] st_set = set(['a', 'a', 'b', 'a', 'b', 'c']) dic = {} for i in st_set: cont = str_list.count(i) dic[i] = cont print(dic) """ 請利用Python內置的hex()函數把一個整數轉換成十六進制表示的字符串: """ n1 = 233 n2 = 1000 print(hex(n1), hex(n2)) """ 請定義一個函數quadratic(a, b, c),接收3個參數,返回一元二次方程 ax^2+bx+c=0 的兩個解。 計算平方根可以調用math.sqrt()函數 """ import math def quadratic(a, b, c): b2 = b ** 2 - 4*a*c if not isinstance(a + b + c, (int, float)): raise TypeError('error type') if b2 >= 0: ma_x1 = math.sqrt(b ** 2 - 4*a*c) x1 = (-b - ma_x1) / (2 * a) x2 = (-b + ma_x1) / (2 * a) print("x1=%.2f ,x2=%.2f" % (x1, x2)) else: print("無解") quadratic(1, 5, 5) """ 以下函數允許計算兩個數的乘積,請稍加改造,變成可接收一個或多個數並計算乘積: def product(x, y): return x * y """ def product(*arges): if len(arges) == 0: raise TypeError('參數不能爲空, 否則沒有意義!') s = 1 for i in arges: if not isinstance(i, (int, float)): raise TypeError('error type') s = i * s #return s print(s) product(10, 25) """ 請編寫move(n, a, b, c)函數,它接收參數n,表示3個柱子A、B、C中第1個柱子A的盤子數量,然後打印出把所有盤子從A藉助B移動到C的方法,例如: """ def move(n, a, b, c): if n < 0: product("請輸入大於0") elif n == 1: print(a, '-->', c) else: move(n - 1, a, c, b) # 1, A, B, C move(1, a, b, c) #1, A, B, C move(n - 1, b, a, c) #1, A, B, C move(2, 'A', 'B', 'C') """ 利用切片操作,實現一個trim()函數,去除字符串首尾的空格,注意不要調用str的strip()方法: """ def trim(s): if s[:1] == ' ': s = s[1:] print(s) elif s[-1:] == ' ': s = s[:-1] print(s) elif s[:1] == ' ' and s[-1:] == ' ': s = s[1:-1] print(s) trim(" abc2" ) """ 請使用迭代查找一個list中最小和最大值,並返回一個tuple: """ def suh(L): if not isinstance(L, (list, tuple)): raise TypeError('param must be a list') max_L = min_L = L[0] for i in L: if max_L < i: max_L = i elif min_L > i: min_L = i print(min_L) print(max_L) suh([8, 2, 4, 5]) """ 如果list中既包含字符串,又包含整數,由於非字符串類型沒有lower()方法,所以列表生成式會報錯: >>> L = ['Hello', 'World', 18, 'Apple', None] >>> [s.lower() for s in L] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <listcomp> AttributeError: 'int' object has no attribute 'lower' 使用內建的isinstance函數可以判斷一個變量是不是字符串: >>> x = 'abc' >>> y = 123 >>> isinstance(x, str) True >>> isinstance(y, str) False 請修改列表生成式,通過添加if語句保證列表生成式能正確地執行: # -*- coding: utf-8 -*- L1 = ['Hello', 'World', 18, 'Apple', None] L2 = ?? """ L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [s.lower() for s in L1 if isinstance(s, str)] print(L2) """ 楊輝三角定義如下: 1 / \ 1 1 / \ / \ 1 2 1 / \ / \ / \ 1 3 3 1 / \ / \ / \ / \ 1 4 6 4 1 / \ / \ / \ / \ / \ 1 5 10 10 5 1 把每一行看做一個list,試寫一個generator,不斷輸出下一行的list: # 期待輸出: # [1] # [1, 1] # [1, 2, 1] # [1, 3, 3, 1] # [1, 4, 6, 4, 1] # [1, 5, 10, 10, 5, 1] # [1, 6, 15, 20, 15, 6, 1] # [1, 7, 21, 35, 35, 21, 7, 1] # [1, 8, 28, 56, 70, 56, 28, 8, 1] # [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] """ def triangles(n): L = [1] m = 0 while n > m: yield L p = [L[a] + L[a + 1] for a in range(len(L) - 1)] #print(p) L = [1] + p + [1] m +=1 for i in triangles(11): print(i) """ 利用map()函數,把用戶輸入的不規範的英文名字,變爲首字母大寫,其他小寫的規範名字。輸入:['adam', 'LISA', 'barT'],輸出:['Adam', 'Lisa', 'Bart']: """ def normalize(name): name = name.lower() name = name.title() return name L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2) """ Python提供的sum()函數可以接受一個list並求和,請編寫一個prod()函數,可以接受一個list並利用reduce()求積: """ from functools import reduce def prod(G): def fn(x, y): return x * y return reduce(fn, G) # def f(): retuen x*y reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) print("3 * 5 * 7 * 9 =", prod([3, 5, 7, 9])) """ 利用map和reduce編寫一個str2float函數,把字符串'123.456'轉換成浮點數123.456: """ def str2float(s): for i in range(len(s)): if s[i] == '.': n = i def num1(x, y = 0): return x * 10 + y Digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def digit(x): return Digits[x] return reduce(num1, map(digit, s[ : n])) + reduce(num1, map(digit, s[n + 1 : ])) / pow(10, (len(s) - n - 1)) print("str2float('123.456') =", str2float('123.456')) if abs(str2float('123.456') - 123.456) < 0.00001: print('測試成功!') else: print('測試失敗!') """ 假設我們用一組tuple表示學生名字和成績: L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] 請用sorted()對上述列表分別按名字排序: """ L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] def by_name(t): m = t[0] return m def by_score(t): n=-t[1] return n L1 = sorted(L, key=by_score) L2 = sorted(L, key=by_name) print(L1) print(L2) """ 回數是指從左向右讀和從右向左讀都是一樣的數,例如12321,909。請利用filter()篩選出回數: """ def is_palindrome(n): c = 0 for i in range(len(str(n))): if str(n)[i] != str(n)[-i-1]: c = c+1 return c == 0 #測試 output = filter(is_palindrome, range(1, 1000)) print('1~1000:', list(output)) if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]: print('測試成功!') else: print('測試失敗!') """ def count(): fs = [] for i in range(1, 4): def f(): return i*i fs.append(f) return fs f1 = count()[0] print(f1()) 不加括號函數不執行。 利用閉包返回一個計數器函數,每次調用它返回遞增整數: """ def createCounter(): f = [] def counter(): f.append(counter) return len(f) return counter # 測試: counterA = createCounter() print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5 counterB = createCounter() if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]: print('測試通過!') else: print('測試失敗!') """ 請用匿名函數改造下面的代碼: def is_odd(n): return n % 2 == 1 L = list(filter(is_odd, range(1, 20))) print(L) """ L = list(filter(lambda n:n % 2 ==1 , range(1, 20))) print(L) """ 請設計一個decorator,它可作用於任何函數上,並打印該函數的執行時間: """ import time, functools def metric(fn): @functools.wraps(fn) def wrapper(*args, **kw): start = time.time() re = fn(*args, **kw) end = time.time() print('%s executed in %s ms' % (fn.__name__, end-start)) return fn(*args, **kw) return wrapper # 測試 @metric def fast(x, y): time.sleep(0.0012) return x + y; @metric def slow(x, y, z): time.sleep(0.1234) return x * y * z; f = fast(11, 22) s = slow(11, 22, 33) if f != 33: print('測試失敗!') elif s != 7986: print('測試失敗!') """ 請把下面的Student對象的gender字段對外隱藏起來,用get_gender()和set_gender()代替,並檢查參數有效性: class Student(object): def __init__(self, name, gender): self.name = name self.gender = gender """ class Student(object): def __init__(self, name, gender): self.name = name self.__gender = gender def get_gender(self): return self.__gender def set_gender(self, gender): self.__gender = gender bart = Student('Bart', 'male') print(bart.name, bart.get_gender()) if bart.get_gender() != 'male': print('測試失敗!') else: bart.set_gender('female') if bart.get_gender() != 'female': print('測試失敗!') else: print('測試成功!') """ 爲了統計學生人數,可以給Student類增加一個類屬性,每創建一個實例,該屬性自動增加: """ class Student(object): count = 0 def __init__(self, name): self.name = name Student.count+=1 # 測試: if Student.count != 0: print('測試失敗!') else: bart = Student('Bart') if Student.count != 1: print('測試失敗!') else: lisa = Student('Bart') if Student.count != 2: print('測試失敗!') else: print('Students:', Student.count) print('測試通過!') """ 請利用@property給一個Screen對象加上width和height屬性,以及一個只讀屬性resolution: """ class Screen(object): @property def width(self): return self._width @width.setter def width(self, width_value): self._width = width_value @property def height(self): return self._height @height.setter def height(self, height_value): self._height = height_value @property def resolution(self): return self._width * self._height # 測試: s = Screen() s.width = 1024 s.height = 768 print('resolution =', s.resolution) if s.resolution == 786432: print('測試通過!') else: print('測試失敗!') """" 運行下面的代碼,根據異常信息進行分析,定位出錯誤源頭,並修復: from functools import reduce def str2num(s): return int(s) def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc + x, ns) def main(): r = calc('100 + 200 + 345') print('100 + 200 + 345 =', r) r = calc('99 + 88 + 7.6') print('99 + 88 + 7.6 =', r) main() """ from functools import reduce def str2num(s): s = s.strip() if s.replace('.','').isdigit(): if s.count('.') == 0: return int(s) else: return float(s) else: raise ValueError('input error') def calc(exp): ss = exp.split('+') print('ss=',ss) ns = map(str2num, ss) return reduce(lambda acc, x: acc + x, ns) def main(): r = calc('100 + 200 + 345') print('100 + 200 + 345 =', r) r = calc('99 + 88 + 7.6') print('99 + 88 + 7.6 =', r) main() """ 請將本地一個文本文件讀爲一個str並打印出來: """ #寫入 fpath_wrig = r'C:\Users\Administrator\Desktop\LUOZIX.txt' with open(fpath_wrig, 'w') as f: w = f.write("woshiwshui\n wozainaer \n woyaoshfuu") #追加 fpath_wria = r'C:\Users\Administrator\Desktop\LUOZIX.txt' with open(fpath_wria, 'a') as f: w = f.write("\n1234455") #1查看 fpath = r'C:\Users\Administrator\Desktop\LUOZIX.txt' with open(fpath, 'r') as f: s = f.read() print(s) #2查看 with open(fpath, 'r') as fs: ss = fs.readlines() for x in ss: print(x)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章