第一天
條件判斷練習測試
# 小明身高1.75,體重80.5kg。請根據BMI公式(體重除以身高的平方)幫小明計算他的BMI指數,並根據BMI指數:
# 低於18.5:過輕
# 18.5-25:正常
# 25-28:過重
# 28-32:肥胖
# 高於32:嚴重肥胖
# 用if-elif判斷並打印結果:
def exp_if():
height = 1.75
weight = 80.5
bmi = weight/(height*height)
if bmi<18.5:
print("you BMI is {}".format(bmi))
elif bmi<=25:
print("you BMI is {},正常".format(bmi))
elif bmi<=28:
print("you BMI is {},過重".format(bmi))
elif bmi<=32:
print("you BMI is {},肥胖".format(bmi))
else:
print("you BMI is \t{:.3f},嚴重肥胖".format(bmi))
if __name__ == '__main__':
exp_if()
利用列表或者元組實現循環
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)
##實現計算0+1+2++100
sum=0
for i in range(101):
sum=sum+i
print(sum)
計算100以內所有奇數之和
#法一:
sum=0
for i in range(1,100,2):
sum=sum+i
print (sum)
#法二:
sum=0
i=1
while i<101 :
sum=sum+i
i=i+2
print(sum)
標準化輸出格式打印練習
#請利用循環依次對list中的每個名字打印出Hello, xxx!:
L = ['Bart', 'Lisa', 'Adam']
len=len(L)
for i in range(len):
print("Hello {}".format(L[i]))
利用.format{}實現標準化輸出格式定義
print "{:.2f}".format(3.1415926) #3.14,保留小數點後兩位
print "{:+.2f}".format(3.1415926) #+3.14 帶符號保留小數點後兩位
print "{:+.2f}".format(-10) #-10.00 帶符號保留小數點後兩位
print "{:+.0f}".format(-10.00) #-10 不帶小數
print "{:0>2d}".format(1) #01 數字補零 (填充左邊, 寬度爲2)
print "{:x<2d}".format(1) #1x 數字補x (填充右邊, 寬度爲4)
print "{:x<4d}".format(10) #10xx 數字補x (填充右邊, 寬度爲4)
print "{:,}".format(1000000) #1,000,000 以逗號分隔的數字格式
print "{:.2%}".format(0.12) #12.00% 百分比格式
print "{:.2e}".format(1000000) #1.00e+06 指數記法
print "{:<10d}".format(10) #10 左對齊 (寬度爲10)
print "{:>10d}".format(10) # 10 右對齊 (默認, 寬度爲10)
print "{:^10d}".format(10) # 10 中間對齊 (寬度爲10)
字典使用
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
判斷是否在字典中
def test_dict():
SC={"Anan":"90","Ping":"88","Ling":"83"}
print(SC['Ping'])
print(SC.get('Ping'))
if __name__ == '__main__':
test_dict()
實現輸入一個name 如果在列表中 輸出得分 判斷得分等級 如果沒有輸出該名字不在名單內
def scoretest(score):
if score>90:
achievement ='優秀'
elif score>=80:
achievement ='良好'
elif score >60:
achievement='及格'
else:
achievement='不及格'
return achievement
if __name__ == '__main__':
input_name=input("Please input you name:")
dict_name_and_score={"Anan":"90","Ping":"88","Ling":"55"}
if input_name in dict_name_and_score:
print('{} score is {} belong to {}'.format(input_name,dict_name_and_score[input_name],scoretest(int(dict_name_and_score[input_name]))))
else:
print("{} is not in our Name list".format(input_name))
實現計算園面積s=πr*r
import math
import numpy
def Circular_Area(r):
PI=3.14
s=PI*numpy.square(r)
return(s)
if __name__ == '__main__':
input=input("R is :")
print("The circular area with a radius of {} is:{:.2f}".format(input,Circular_Area(int(input))))
函數quadratic(a, b, c),接收3個參數,返回一元二次方程:ax2 + bx + c = 0
import numpy as np
def quadratic(a,b,c):
x1=(-b+np.sqrt(b*b-4*a*c))/(2*a)
x2=(-b-np.sqrt(b*b-4*a*c))/(2*a)
return(x1,x2)
def main():
quadratic(1,3,-4)
print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))
if quadratic(2, 3, 1) != (-0.5, -1.0):
print('測試失敗')
elif quadratic(1, 3, -4) != (1.0, -4.0):
print('測試失敗')
else:
print('測試成功')
if __name__ == '__main__':
main()
第二天
切片
L=[]
n=1
while n<99:
L.append(n)
n=n+2
print(L)
#取list或者元組的前三個元素
# def test_list():
# L=[]
# n=1
# while n<=99:
# L.append(n)
# n=n+2
# # print(L)
# print(L[:3])
# # return L
# pass
# def test_tuple():
# T=('Anan','Ping','Ling','Zhen')
# # return T
# print(T[:3])
# print(T[::2]) #開始 結束 步長
# if __name__ == '__main__':
# # test_list()
# test_tuple()
列表生成式訓練
L1 = ['Hello', 'World', 18, 'Apple', None]
L2=[]
j=0
for i in range(len(L1)-1):
if isinstance(L1[i],str):
L2.append(L1[i].lower())
j=j+1
if L2 == ['hello', 'world', 'apple']:
print('測試通過!')
else:
print('測試失敗!')
第三天
高階函數
def add(x, y, f):
return f(x) + f(y)
print(add(-5, 6, abs))
def add(x,y,f):
return f(x)+f(y)
def min(x,y,h):
return(h(x)-h(y))
def h(z):
return abs(z)
if __name__ == '__main__':
x=-5
y=6
f=abs
# print(add(h(3),h(2)))
print(min(h(3),h(2),h))
print(min(3,4,h))
map reduace的實現
>map()函數接收兩個參數 一個是函數 一個是Iterable,map將傳入的函數依次作用到序列的每個元素,並把結果作爲Iterator返回
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#function (1) 利用map計算一個列表中數的平方 (2)利用reduace函數把序列[1, 3, 5, 7, 9]變換成整數13579
from functools import reduce
def f(x):
return x*x
def map_test():
r=map(f,[1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
print(list(map(str,[1,2,3,3,45,5,5,4])))
def fn(x,y):
return x*10+y
def reduace_test():
print(reduce(fn,[1,2,5,6]))
pass
if __name__ == '__main__':
# map_test()
reduace_test()
結合MapReduace實現將字符轉化爲數字進行運算
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#function 結合MapReduace實現將字符轉化爲數字進行運算
from functools import reduce
def fn(x,y):
return x*10+y
def char2num(s):
digits={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
return digits[s]
print(reduce(fn,map(char2num,'1456')))
利用map()函數,把用戶輸入的不規範的英文名字,變爲首字母大寫,其他小寫的規範名字。
# -*- coding: utf-8 -*-
def normalize(name):
name.title()
# 測試:
##輸入:['adam', 'LISA', 'barT'],輸出:['Adam', 'Lisa', 'Bart']:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
利用prod()函數實現可以接受一個list並利用reduce()求積:
from functools import reduce
def prod(L):
sumL=1
for i in range(len(L)):
sumL=sumL*L[i]
return sumL
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('測試成功!')
else:
print('測試失敗!')
from functools import reduce
def prod(x,y):
return x*y
result = reduce(prod,[3,5,7,9])
print(result)
把字符串’123.456’轉換成浮點數123.456
def str2float(s):
return float(s)
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('測試成功!')
else:
print('測試失敗!')
利用filter()篩選出回數
def is_palindrome(n):
return str(n)==str(n)[::-1]
# 測試:
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('測試失敗!')
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0]
def by_score(t):
return t[1]
L2 = sorted(L, key=by_score)
print(L2)
匿名函數
關鍵字lambda表示匿名函數,冒號前面的x表示函數參數。
L=list(filter(lambda n :n%2==1,range(1,20)))
print(L)
def is_odd(n):
return n % 2 == 1
L1 = list(filter(is_odd, range(1, 20)))
print(L1)
def is_odd2(n):
return lambda n:n%2==1
L2 = list(filter(is_odd2(0), range(1, 20)))
print(L2)
python內建函數:https://docs.python.org/3/library/functions.html
第四天
實現面相對象編程
# !/usr/bin/env python
# -*- coding: utf-8 -*-
'實現面相對象編程'
class Student(object):
"""docstring for Student"""
def __init__(self, name,score):
self.name=name
self.score=score
def print_score(self):
return '%s,%s'%(self.name,self.score)
def get_grade(self):
if self.score>=90:
return 'A'
elif self.score>=80:
return 'B'
elif self.score>=60:
return 'C'
else:
return 'D'
def main():
anan=Student('Anan',88)
anan.print_score()
print(anan.name,anan.score,anan.get_grade())
if __name__ == '__main__':
main()
'定義私有變量(private)'
class Student(object):
def __init__(self, name,score):
self.__name=name
self.__score=score
def print_score(self):
return '%s,%s'%(self.__name,self.__score)
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def main():
anan=Student('Anan',88)
print(anan.get_name(),anan.get_score())
if __name__ == '__main__':
main()
'訪問限制訓練'
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
return self.__gender
def test():
bart = Student('Bart', 'male')
if bart.get_gender() != 'male':
print('測試失敗!')
else:
bart.set_gender('female')
if bart.get_gender() != 'female':
print('測試失敗!')
else:
print('測試成功!')
if __name__ == '__main__':
test()
繼承和多態
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')
class Cat(Animal):
def run(self):
print('Cat is running...')
def run_twice(animal):
animal.run()
animal.run()
a = Animal()
d = Dog()
c = Cat()
print('a is Animal?', isinstance(a, Animal))
print('a is Dog?', isinstance(a, Dog))
print('a is Cat?', isinstance(a, Cat))
print('d is Animal?', isinstance(d, Animal))
print('d is Dog?', isinstance(d, Dog))
print('d is Cat?', isinstance(d, Cat))
run_twice(c)
爲了統計學生人數,可以給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('測試通過!')
使用slots
使用slots可以限制實例的屬性,只允許對類的實例添加slots定義的屬性
slots不能限制繼承類的實例屬性。如果被繼承的類也需要進行限定需要子類也添加slots的限定
使用@property
IO編程
python讀取文件:
'方法一'
f=open('filename','r')
f.read()
f.close()
'方法二'#-->推薦
with open('filename','r') as f:
f.read()
python寫入文件:
'方法一'
f=open('filename','w')
f.write()
f.close()
'方法二'#-->推薦
with open('filename','w') as f:
f.write('輸入你需要寫入的內容')
方法三:
file=r'filename'
with open(file,'w+') as f:
f.write('輸入你需要寫入的內容')
輸入輸出參數詳解:
‘r’:讀\
‘w’:寫\
‘a’:追加\
‘r+’ == r+w(可讀可寫,文件若不存在就報錯(IOError))\
‘w+’ == w+r(可讀可寫,文件若不存在就創建)\
‘a+’ ==a+r(可追加可寫,文件若不存在就創建)\
對應的,如果是二進制文件,就都加一個b:\
‘rb’ ‘wb’ ‘ab’ ‘rb+’ ‘wb+’ ‘ab+’
正則表達式
\d匹配一個數字\
\w匹配一個字母或數字\
*表示任意個字符(包括0個)\
+表示至少一個字符\
?表示0個或1個字符\
{n}表示n個字符\
{n,m}表示n-m個字符\
A|B可以匹配A或B\
^表示行的開頭\
^\d表示必須以數字開頭\
表示必須以數字結束
案例:正則匹配郵箱
test='[email protected]'
if re.match(r'^[0-9a-zA-Z_.]+@[a-z]+.com$', test):
print('ok')
else:
print('failed')
裝飾器
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def aa(func):
def bb():
print("abc")
result=func()
return bb
@aa
def main():
print("main")
if __name__ == '__main__':
main()
未完待續…