




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、Python 語(yǔ)法教程講義 -第一章、python基礎(chǔ)1、python的源程序,1.1、python的源程序,本質(zhì)上就是一個(gè)特殊格式的文本,可以使用任意文本編輯軟件做python開發(fā)擴(kuò)展名為.py。1.2、第一個(gè)小程序 Print(“hello python”) Print(“hello word”) 在linux中運(yùn)行python源程序:python 01-hellopython.py;1.3、執(zhí)行python程序的三種方式:1.3.1)、python/python 3解釋器/其他解釋器 Python xxx.py; Python3 xxx.py1.3.2)、交互式運(yùn)行python程序也就是
2、在終端中,直接運(yùn)行解釋器,而不需要傳入文件名,在python 的shell中,直接輸入終端命令。 優(yōu)點(diǎn):適合驗(yàn)證局部代碼;缺點(diǎn):不能保存代碼,不適合大量代碼文件。 操作:linux下,直接輸入python進(jìn)入pythonpython3的解釋器shell,輸入python程序。 1.01的365次方:1.01*365 /退出解釋器:exit()或者ctrl+d交互式執(zhí)行python程序時(shí),推薦使用ipython,通常是我們首選的shell: 優(yōu)點(diǎn):自然后動(dòng)補(bǔ)全、自動(dòng)縮進(jìn)、支持bash shell、內(nèi)置了許多功能和函數(shù)、支持很多l(xiāng)inux命令 操作:linux下,直接輸入ipythoni pyth
3、on3進(jìn)入python的解釋器shell,輸入python程序。 1.3.3)、集成開發(fā)環(huán)境IDE(集成了開發(fā)環(huán)境需要的所有命令); pycham是一款非常優(yōu)秀的python集成開發(fā)環(huán)境,可以在window、linux、macos中使用,2、算術(shù)運(yùn)算 加+、減-、乘*、除/、取整/、取余%、取冪*;3、變量 數(shù)據(jù)類型:數(shù)字型:整數(shù)、浮點(diǎn)數(shù)、布爾值、復(fù)數(shù); 非數(shù)字型:字符串、列表、元組、字典 Python2.x版本整型包括:int、long。Type(z*89);3.0以后不區(qū)分,都為int;注:type函數(shù)可以查看數(shù)據(jù)類型;循環(huán)的語(yǔ)法:If : Else :While :For i in ra
4、nge(3):命名規(guī)范:1、只能包括字母、數(shù)字、下劃線;2、只能以字母或者下劃線開頭;3、不能包括空格;4、不能與關(guān)鍵字沖突;字符串:用單引號(hào)、雙引號(hào)括起來(lái)的,都是字符串; Print(“fvr”+str(age)+”fvrv”),使用str()來(lái)轉(zhuǎn)換為字符串;注:1)、變量名.title(),將變量名的首字母轉(zhuǎn)換成大寫字母;使用+來(lái)拼接字符串;nt換行退格; 2)、刪除空格,.rstrip(); 3)、print可以使用多個(gè),分離,連續(xù)輸出,但是使用,會(huì)添加空格。Print(scdc,mr) 4)、print(第0天體重為:1.format(day,height) 5)、注釋單行/多行代碼:
5、選中+ctrl+/ 3.1、數(shù)據(jù)類型轉(zhuǎn)換 字符串轉(zhuǎn)int: num=21int1=int(num)print(int1)4、列表 列表是一系列按特定順序排列的元素組成,可以創(chuàng)建包含任何沒(méi)有關(guān)聯(lián)的元素。4.1、創(chuàng)建列表Bicycle=trek,rgtg,cecPrintbicycle4.2、訪問(wèn)、使用列表元素 bicycle=efer,cec,cprint(bicycle0.title()4.3、添加元素 末尾添加元素:.append(efvrf) 支持動(dòng)態(tài)添加數(shù)據(jù): bicycle=bicycle.append(ecece)print(bicycle)支持動(dòng)態(tài)插入數(shù)據(jù):.insert(1,ed
6、ed)4.4、刪除元素 1)、刪除任意位置元素 bicycle=regr,uyu,fgtghdel bicycle1print(bicycle regr, fgtgh 2)、刪除任意位置元素 bicycle=regr,uyu,fgtghlastBicycle=bicycle.pop(1)print(bicycle)print(lastBicycle)regr, uyufgtgh 3)、根據(jù)值刪除元素 bicycle=regr,uyu,fgtghbicycle.remove(uyu)print(bicycle) 注:remove只能刪除第一個(gè)指定值的元素,需要循環(huán)判斷; 4.5、元素處理 1)、
7、對(duì)元素永久性排序 按字母排序:bicycle.sort() 按字母排反序:bicycle.sort(reverse=True) 2)、對(duì)元素排序且不影響原數(shù)據(jù): bicycle=regr,uyu,fgtghnewB=sorted(bicycle)newB=sorted(bicycle,reverse=True)print(bicycle)print(newB)4.6、列表信息 Len(bicycle)4.7、操作列表4.7.1、遍歷列表 bicycles=regr,uyu,fgtghfor bicycle in bicycles: print(bicycle)regruyufgtgh4.7.2
8、、創(chuàng)建數(shù)字列表 1)、使用range ui=range(2,6)for b in range(1,9): print(b)print(ui) 2)、使用list將range轉(zhuǎn)換為列表、指定步長(zhǎng)number=list(range(1,9,2)print(number)3)、統(tǒng)計(jì)列表 max(number)min(number)sum(number) 4)、使用列表解析創(chuàng)建列表 squre=value*2 for value in range(1,9)print(squre)4.7.3、使用列表一部分 1)、切片 squre=list(range(1,9)num=squre2:7print(squ
9、re)print(num)3, 4, 5, 6, 72)、復(fù)制列表 squre=list(range(1,9)num=squre:4.8、元組不可變的列表稱為元組4.8.1、定義元組與列表不一樣的是需要使用括號(hào)來(lái)定義元組 num=(2,3,5,6,7,5,3,9)5、控制語(yǔ)句5.1、if語(yǔ)句If xxx : Xxx XxxElse: Xxx Xxx xxxxxxxx注:1)、python比較不區(qū)分大小寫; 2)、使用and 和or判斷多個(gè)條件 3)、使用num=er,vf,fbrb,hytif vf in num: print(OK) 檢測(cè)是否包含在列表中num=er,vf,fbrb,hyti
10、f vf not in num: print(OK) if xxx: xxx elif xxx xxx5.2、while 循環(huán)5.2.1、使用break立即退出循環(huán)5.2.2、使用continue跳到開頭繼續(xù)判斷執(zhí)行5.2.3、使用while判斷列表是否為空 listnew=de,gtg,rfrf,hyh,vtvtwhile listnew: print(listnew) listnew.pop()6、字典 字典包括一系列的鍵值對(duì),通過(guò)鍵可以訪問(wèn)值,值可以是數(shù)字、字符串甚至字典6.1、創(chuàng)建字典 client=color:green,size:5print(clientcolor+*+str(c
11、lientsize)6.2、添加鍵值對(duì) client=color:green,size:5clientui=newclientsize0=9print(clientcolor+*+str(clientsize)+*+clientui+*+str(clientsize0)6.3、刪除鍵值對(duì)del clientcolor6.4、遍歷字典 client=color:green,size:5clientui=newclientsize0=9for key,value in client.items():print(key:+key+-value:+str(value) 排序遍歷 for key,val
12、ue in sorted(client.items(),reverse=True): print(key:+key+-value:+str(value)只遍歷值for value in client.values(): print(value)遍歷時(shí)過(guò)濾表中重復(fù)的元素 for value in set(client.values():7、函數(shù): 定義:Def add(x,y):Return (x+y)調(diào)用:add(1,2)注:1)、input函數(shù) 讓用戶輸入?yún)?shù),存儲(chǔ)在變量中,可以添加信息提示用戶輸入:num=input(請(qǐng)輸入:)print(num) 2)、方法split() 以空格為分隔符
13、將字符串分拆成多個(gè)部分, 并將這些部分都存儲(chǔ)到一個(gè)列表中。7.1、關(guān)鍵字實(shí)參定義:Def add(x,y):Return (x*80+y)調(diào)用:add(x=1,y=2) 7. 2、形參默認(rèn)值: def addInt(x=20,y=1): 7.3、實(shí)參可選 def addInt(x=20,y=1,z=): return (x+y*199)print(addInt(x=100,y=0)7.4、返回字典 def build_person(first_name, last_name): person = first: first_name, last: last_name return person
14、7.5、字典做參數(shù) def greet_users(names):for name in names:msg = Hello, + name.title() + !print(msg) usernames = hannah, ty, margotgreet_users(usernames)7.6、列表的副本傳遞給函數(shù)可以像下面這樣做:function_name(list_name:) 7.7、傳遞任意多實(shí)參 def make_pizza(*toppings):打印顧客點(diǎn)的所有配料print(toppings)make_pizza(pepperoni)make_pizza(mushrooms,
15、green peppers, extra cheese)7.8、結(jié)合使用位置實(shí)參和任意數(shù)量實(shí)參 def make_pizza(size, *toppings):概述要制作的比薩print(nMaking a + str(size) +-inch pizza with the following toppings:)for topping in toppings:print(- + topping)make_pizza(16, pepperoni)make_pizza(12, mushrooms, green peppers, extra cheese)7.9、使用任意數(shù)量的關(guān)鍵字實(shí)參 def
16、build_profile(first, last, *user_info):創(chuàng)建一個(gè)字典, 其中包含我們知道的有關(guān)用戶的一切profile = profilefirst_name = firstprofilelast_name = last for key, value in user_info.items():profilekey = valuereturn profileuser_profile = build_profile(albert, einstein,location=princeton,field=physics)print(user_profile)7.10、將函數(shù)導(dǎo)入模塊
17、中 1)、導(dǎo)入整個(gè)模塊 模塊 是擴(kuò)展名為.py的文件, 包含要導(dǎo)入到程序中的代碼。 import addIntPrj /導(dǎo)入模塊print(addIntPrj.addInt(2,4) 2)、導(dǎo)入函數(shù) from addIntPrj import addIntprint(addInt(1,2) 3)、使用as 給函數(shù)指定別名 from pizza import make_pizza as mpmp(16, pepperoni)mp(12, mushrooms, green peppers, extra cheese) 4)、使用as給模塊指定別名 import pizza as pp.make_p
18、izza(16, pepperoni)p.make_pizza(12, mushrooms, green peppers, extra cheese 5)、導(dǎo)入模塊所有函數(shù) from pizza import *make_pizza(16, pepperoni)make_pizza(12, mushrooms, green peppers, extra cheese)8、類8.1、創(chuàng)建類 Class 類名(): 成員 class Dog(): def _init_(self, name, age): /初始化屬性 = name /self相當(dāng)于thisself.age =
19、age def sit(self):print(.title() + is now sitting.)def roll_over(self):print(.title() + rolled over!)8.2、創(chuàng)建類的實(shí)例 class Dog(): my_dog = Dog(willie, 6) /創(chuàng)建類的實(shí)例 print(My dogs name is + my_.title() + .) /訪問(wèn)類的屬性 print(My dog is + str(my_dog.age) + years old.)my_dog.sit() /調(diào)用方法my_
20、dog.roll_over()8.3、屬性賦予默認(rèn)值 def _init_(self, make, model, year):初始化描述汽車的屬性self.make = makeself.model = modelself.year = year self.odometer_reading = 0 /賦予默認(rèn)值8.4、繼承 class Car(): /創(chuàng)建父類def _init_(self, make, model, year):self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_
21、descriptive_name(self):long_name = str(self.year) + + self.make + + self.modelreturn long_name.title()def read_odometer(self):print(This car has + str(self.odometer_reading) + miles on it.)def update_odometer(self, mileage):if mileage = self.odometer_reading:self.odometer_reading = mileageelse:print
22、(You cant roll back an odometer!)def increment_odometer(self, miles):self.odometer_reading += miles /創(chuàng)建子類 class ElectricCar(Car): def _init_(self, make, model, year):初始化父類的屬性 super()._init_(make, model, year) /創(chuàng)建子類實(shí)例 my_tesla = ElectricCar(tesla, model s, 2016)print(my_tesla.get_descriptive_name()1)
23、、創(chuàng)建子類時(shí), 父類必須包含在當(dāng)前文件中, 且位于子類前面。2)、方法_init_() 接受創(chuàng)建Car 實(shí)例所需的信息。3)、super() 是一個(gè)特殊函數(shù), 幫助Python將父類和子類關(guān)聯(lián)起來(lái)。 這行代碼讓Python調(diào)用ElectricCar 的父類的方法_init_() , 讓ElectricCar 實(shí)例包含父類的所有屬性。 父類也稱為超類 (superclass) , 名稱super因此而得名。4)、給子類定義新的屬性 class Car():class ElectricCar(Car):def _init_(self, make, model, year):super()._ini
24、t_(make, model, year) self.battery_size = 70 def describe_battery(self):print(This car has a + str(self.battery_size) + -kWh battery.)8.4.1、重寫父類方法 對(duì)于父類的方法, 只要它不符合子類模擬的實(shí)物的行為, 都可對(duì)其進(jìn)行重寫。 為此, 可在子類中定義一個(gè)這樣的方法, 即它與要重寫的父類方法同名。 這樣, Python將不會(huì)考慮這個(gè)父類方法, 而只關(guān)注你在子類中定義的相應(yīng)方法; 假設(shè)Car 類有一個(gè)名為fill_gas_tank() 的方法, 它對(duì)全電動(dòng)汽車
25、來(lái)說(shuō)毫無(wú)意義, 因此你可能想重寫它。 下面演示了一種重寫方式: def ElectricCar(Car):def fill_gas_tank():print(This car doesnt need a gas tank!)8.4.2、將實(shí)例用作屬性不斷給ElectricCar 類添加細(xì)節(jié)時(shí), 我們可能會(huì)發(fā)現(xiàn)其中包含很多專門針對(duì)汽車電瓶的屬性和方法。 在這種情況下, 我們可將這些屬性和方法提取出來(lái), 放到另一個(gè)名為Battery 的類中, 并將一個(gè)Battery 實(shí)例用作ElectricCar 類的一個(gè)屬性:class Car():class Battery():def _init_(self
26、, battery_size=70):self.battery_size = battery_sizedef describe_battery(self):print(This car has a + str(self.battery_size) + -kWh battery.)/電動(dòng)車獨(dú)特屬性class ElectricCar(Car):def _init_(self, make, model, year):super()._init_(make, model, year)self.battery = Battery()my_tesla = ElectricCar(tesla, model
27、s, 2016)print(my_tesla.get_descriptive_name()my_tesla.battery.describe_battery()注:一個(gè)類里面可以包括多個(gè)類8.5、導(dǎo)入類 from car import Car /導(dǎo)入類模塊my_new_car = Car(audi, a4, 2016) /創(chuàng)建類實(shí)例print(my_new_car.get_descriptive_name()my_new_car.odometer_reading = 23my_new_car.read_odometer()8.5.1、導(dǎo)入模塊中的某個(gè)類單個(gè).py文件可以包括多個(gè)類,導(dǎo)入模塊時(shí)可
28、以只導(dǎo)入我們需要的類 from car import ElectricCarmy_tesla = ElectricCar(tesla, model s, 2016)print(my_tesla.get_descriptive_name()8.5.2、在一個(gè)模塊中導(dǎo)入多個(gè)類 from car import ElectricCarmy_tesla = ElectricCar(tesla, model s, 2016)print(my_tesla.get_descriptive_name()8.5.3、導(dǎo)入整個(gè)模塊 import car my_beetle = car.Car(volkswagen,
29、 beetle, 2016)print(my_beetle.get_descriptive_name() my_tesla = car.ElectricCar(tesla, roadster, 2016)print(my_tesla.get_descriptive_name()8.5.4、導(dǎo)入模塊每個(gè)類 import car import *8.5.5、將一個(gè)類存儲(chǔ)在幾個(gè)模塊主模塊:car.py class Car():-snip分部模塊:electric_car.py from car import Carclass Battery():-snip-class ElectricCar(Car
30、):-snip使用模塊: from car import Carfrom electric_car import ElectricCar8.6、使用python標(biāo)準(zhǔn)庫(kù) 下面來(lái)看模塊collections 中的一個(gè)類OrderedDict from collections import OrderedDict favorite_languages = OrderedDict() favorite_languagesjen = pythonfavorite_languagessarah = cfavorite_languagesedward = rubyfavorite_languagesphil
31、 = pythonfor name, language in favorite_languages.items():print(name.title() + s favorite language is +language.title() + .)9、文件和異常 9.1、讀取整個(gè)文件 with open(111.txt) as file_object: /使用with,可以在結(jié)束時(shí)自動(dòng)關(guān)閉文件 contents = file_object.read() print(contents) 相比于原始文件, 該輸出唯一不同的地方是末尾多了一個(gè)空行。 為何會(huì)多出這個(gè)空行呢? 因?yàn)閞ead() 到達(dá)文件
32、末尾時(shí)返回一個(gè)空字符串, 而將這個(gè)空字符串顯示出來(lái)時(shí)就是一個(gè)空行。 要?jiǎng)h除多出來(lái)的空行, 可在print 語(yǔ)句中使用rstrip(): with open(pi_digits.txt) as file_object:contents = file_object.read()print(contents.rstrip() rstrip() 刪除(剝除) 字符串末尾的空白9.1.1、文件路徑file_path = C:Usersehmatthesother_filestext_filesfilename.txtwith open(file_path) as file_object:9.2、逐行讀取
33、 filename = pi_digits.txt with open(filename) as file_object:for line in file_object:print(line)9.3、使用列表存儲(chǔ)文件filename = pi_digits.txtwith open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip()readlines() 從文件中讀取每一行, 并將其存儲(chǔ)在一個(gè)列表中; 接下來(lái), 該列表被存儲(chǔ)到變量lines 中9.4、寫
34、入文件 filename = programming.txtwith open(filename, w) as file_object: file_object.write(I love programming.)9.4.1、寫入多行filename = programming.txtwith open(filename, w) as file_object:file_object.write(I love programming.)file_object.write(I love creating new games.)9.4.2、附加到文件末尾如果你要給文件添加內(nèi)容, 而不是覆蓋原有的內(nèi)容, 可以附加模式 打開文件 filename = programming.txt with open(filename, a) as file_object:file_object.write(I also love finding meani
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024基于類腦計(jì)算人工智能安全
- 口語(yǔ)交際:轉(zhuǎn)述 教學(xué)設(shè)計(jì)-2023-2024學(xué)年語(yǔ)文四年級(jí)下冊(cè)統(tǒng)編版
- 2025年中考道德與法治全真模擬卷3(含答案)
- 攝影基礎(chǔ)知識(shí)培訓(xùn)課件
- 出資贈(zèng)與合同范本
- 2025年節(jié)約糧食標(biāo)準(zhǔn)教案5篇
- 員工薪酬福利計(jì)劃
- 加強(qiáng)社區(qū)“鄰里守望”機(jī)制建設(shè)計(jì)劃
- 加強(qiáng)幼兒園學(xué)生創(chuàng)新思維能力的工作計(jì)劃
- 教學(xué)評(píng)價(jià)中的定量與定性計(jì)劃
- 林木林地權(quán)屬爭(zhēng)議處理申請(qǐng)書
- 阿里云+跨國(guó)企業(yè)上云登陸區(qū)(Landing+Zone)白皮書
- 家鄉(xiāng)鹽城城市介紹江蘇鹽城介紹課件
- 市政工程施工安全檢查標(biāo)準(zhǔn)
- 銀行整村授信工作經(jīng)驗(yàn)材料工作總結(jié)匯報(bào)報(bào)告2篇
- 四川事業(yè)單位工作人員收入分配制度改革實(shí)施意見
- 陜西省2023第二屆長(zhǎng)安杯大中小學(xué)國(guó)家安全知識(shí)競(jìng)賽題庫(kù)及答案
- 基建礦井應(yīng)急救援預(yù)案之綜合應(yīng)急預(yù)案匯編(完整版)資料
- GA/T 830-2021尸體解剖檢驗(yàn)室建設(shè)規(guī)范
- 《PEP英語(yǔ)六年級(jí)下冊(cè)Unit3Readandwrite》東城虎英小學(xué)王曉惠
- GB/T 3778-2021橡膠用炭黑
評(píng)論
0/150
提交評(píng)論