emmm,這部分學的很累,也花了很長時間,但是工欲善其事必先利其器,基礎是必不可少的。Python的語法相對來說比較接近自然語言,所以也比較好理解。但是,Python對空格很敏感,可能缺少一個空格就能導致整個程序運行不出來,所以,好的書寫習慣有利于提高自己的編程效率。理論學完之后不一定能全部記住,需要通過大量的實踐來鞏固和加深。電子書資源見文尾,下次為大家推薦一些值得關注的公眾號~
1、安裝
安裝Python? :?http://python.org/downloads/

安裝文本編輯器 :http://geany.org/
單擊Download下的Releases, 找到安裝程序geany-1.25_setup.exe或類似的文件。 下載安裝程序后, 運行它并接受所有的默認設置。

1)新建:安裝完成后,新建文件,輸入代碼? print('Hello world!')
2)保存:文件命名以.py結束,.py指出這是一個Python程序;
3)運行:可在編輯器中直接‘執(zhí)行’,也可以在windows終端運行

2、變量和簡單的數(shù)據(jù)類型
1)變量:存儲一個值
●??變量名只能包含字母、 數(shù)字和下劃線,可以字母或下劃線打頭, 但不能以數(shù)字打頭
●??變量名不能包含空格, 但可使用下劃線來分隔其中的單詞
●??不要將Python關鍵字和函數(shù)名用作變量名
●??變量名應既簡短又具有描述性
●??慎用小寫字母l和大寫字母O, 因為它們可能被人錯看成數(shù)字1和0
2)字符串:一系列字符
●??用引號括起的都是字符串,引號可以是單引號, 也可以是雙引號
●??修改字符串大小寫:全部大寫 upper(),全部小寫lower(),首字母大寫title()
●??連接字符串:+
●??添加空白:制表符? \t,換行符? \n
●??刪除空白:刪除字符串開頭和末尾多余的空白 rstrip(),剔除字符串開頭的空白, 或同時剔除字符串兩端的空白? lstrip() 和strip()
3)數(shù)字
●??整數(shù):可進行+-*/運算,用兩個乘號表示乘方運算
●??浮點數(shù):帶小數(shù)點的數(shù)
●??避免類型錯誤:轉換為字符型 str(),不同類型變量不可以直接相加減
4)注釋:# ctrl+E
5)Python之禪:在Python終端會話中執(zhí)行命令import this

3、列表
由一系列按特定順序排列的元素組成,在Python中, 用方括號[ ] 來表示列表, 并用,逗號來分隔其中的元素
1)訪問列表元素
在Python中, 第一個列表元素的索引為0, 而不是1,索引指定為-1 , 可讓Python返回最后一個列表元素,以此倒推
bicycles=['trek','cannondale','redline']
print(bycycle[0])
2)添加、修改和刪除列表中的元素
●??修改:
bicycles=['trek','cannondale','redline']
bycycle[0]=‘honda’
print(bicycles)
●??添加:列表附加元素時, 它將添加到列表末尾 append(),列表的任何位置添加新元素 insert(位置,內容)
●??刪除:知道要刪除元素的位置 del,從列表中刪除, 并接著使用它的值 pop(),知道要刪除的元素的值 remove()
3)組織列表
●??永久性排序:sort(),反向排序 sort(reverse=True)
●??臨時排序:sorted(),反向排序 sorted(reverse=True)
●??反轉元素排列順序:reverse()
●??確定列表長度:len()
4、操作列表
1)遍歷整個列表:for 變量 in列表:縮進
●??編寫for 循環(huán)時, 對于用于存儲列表中每個值的臨時變量, 可指定任何名稱
●??在for 循環(huán)中, 可對每個元素執(zhí)行任何操作
●??位于for 語句后面且屬于循環(huán)組成部分的代碼行, 一定要縮進
●??for 語句末尾的冒號告訴Python, 下一行是循環(huán)的第一行,一定要加
2)創(chuàng)建數(shù)值列表
●??生成一系列的數(shù)字:range(開始,截止,步長),指定的第一個值開始數(shù), 并在到達你指定的第二個值后停止, 輸出不包含第二個值
●??轉換為列表:函數(shù)list() 將range() 的結果直接轉換為列表 list(range(1,3))
●??統(tǒng)計計算:最大值 max(),最小值 min(),求和 sum()
●??列表解析:將for 循環(huán)和創(chuàng)建新元素的代碼合并成一行, 并自動附加新元素,for 語句末尾沒有冒號
3)使用部分列表
●??切片:[起始,終止(不包含該元素)],若沒有指定第一個索引, 自動從列表開頭開始提取,若沒有終止元素,則提取列表末尾的所有元素;負數(shù)索引返回離列表末尾相應距離的元素,如players[-3:]返回列表players最后三個元素
●??遍歷切片 [:]
●??復制列表:可創(chuàng)建一個包含整個列表的切片, 方法是同時省略起始索引和終止索引 [:]
4)元組
列表適用于存儲在程序運行期間可能變化的數(shù)據(jù)集,列表是可以修改的,元組是不可修改的列表。
●??定義:元組看起來猶如列表, 但使用圓括號()來標識
●??遍歷:for循環(huán)
●??修改元祖變量:重新定義整個元組
5)代碼格式
●??縮進:每級縮進4個空格
●??行長:小于80個字符
5、if語句
1)條件測試
每條if 語句的核心都是一個值為True 或False 的表達式, 這種表達式被稱為條件測試
●??檢查是否相等:=? 區(qū)分大小寫
●??檢查是否不相等: !=
●??檢查多個條件:and? or
●??檢查特定值是否包含在列表:? in/not in
●??布爾表達式:條件測試的別名
2)if語句
●??if-else語句
for megican in megicans:
????????if megican=='alice':
????????????????print(megican.upper())
????????else:
????????????????print(megican.title())
●??if-elif-else 結構
相當于if-else if-else
3)用if語句處理列表
●??檢查特殊元素
●??確定列表不是空的
6、字典
1)使用字典
字典:是一系列鍵—值對 。 每個鍵 都與一個值相關聯(lián), 你可以使用鍵來訪問與之相關聯(lián)的值,字典用放在花括號{} 中的一系列鍵—值對表示。
●??訪問字典:
alien_0={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
●??添加鍵值對
alien_0={'color':'green','points':5}
print(alien_0)
alien_0['x_position']=25
alien_0['y_position']=5
print(alien_0)
●??刪除鍵值對 del alien_0['points']
2)遍歷字典 for 循環(huán)
●??遍歷所有鍵值對
user_0={
????????'user_name':'efermi',
????????'first':'enrico',
????????'last':'fermi',
????????}
for key,value in user_0.items():
????????print('\nKey: '+key)
????????print('Value: '+value)
●??遍歷所有鍵
for key in user_0.keys():
●??按順序遍歷字典中所有鍵
for key in sorted(user_0.keys()):
●??遍歷所有值
for value in user_0.valuses():
3)嵌套
●??將一系列字典存儲在列表中, 或將列表作為值存儲在字典中, 這稱為嵌套
user_0={
????????'user_name':'amily',
????????'first':'ami',
????????'last':'lily',
????????}
user_1={
????????'user_name':'efermi',
????????'first':'enrico',
????????'last':'fermi',
????????}
users=[user_0,user_1]
for user in users:
????????print(user)
●??在字典中存儲列表
pizza={
????????'crust':'thick',
????????'toppings':['mushrooms','extra cheese'],
????????}
print('You ordered a '+pizza['crust']+'-crust pizza '+'with the follwing toppings:')
for topping in pizza['toppings']:
????????print('\t'+topping)
●??在字典中嵌套字典
users={
????????'user_0':{
????????????????'first':'amily',
????????????????'last':'smith',
????????????????'location':'princeton',
????????????????},
????????'user_1':{
????????????????'first':'efermi',
????????????????'last':'curie',
????????????????'location':'paris',
????????????????},
????????}
for username,user_info in users.items():
????????print('\nUsername: '+username)
????????full_name=user_info['first'] + ' '+user_info['last']
????????location=user_info['location']
????????print('\tFull name: '+full_name.title())
????????print('\tLocation: '+location.title())
7、用戶輸入和while循環(huán)
1)input()函數(shù)
●??原理
函數(shù)input() 讓程序暫停運行, 等待用戶輸入一些文本。 獲取用戶輸入后, Python將其存儲在一個變量中。
message=input('Tell me something, and i will repeat it back to you: ')
print(message)
有時候, 提示可能超過一行, 例如, 你可能需要指出獲取特定輸入的原因。 在這種情況下, 可將提示存儲在一個變量中, 再將該變量傳遞給函數(shù)input()
message='Tell me something, and i will repeat it back to you'
message+='\nWhat do you want to say? '
something=input(messgae)
print('\nHello, '+something+'!')
●??int()獲取數(shù)值輸入
使用函數(shù)input() 時,Python將用戶輸入解讀為字符串,函數(shù)int() 將數(shù)字的字符串表示轉換為數(shù)值表示。
age=input('How old are you? ')
age=int(age)
if age>=18:
????????print("\nYou're old enough to ride!")
else:
????????print("\nYou'll be able to ride when you're a little order.")
●??求模運算符: % 兩個數(shù)相除并返回余數(shù)
如果一個數(shù)可被另一個數(shù)整除, 余數(shù)就為0, 因此求模運算符將返回0,可利用這一點來判斷一個數(shù)是奇數(shù)還是偶數(shù)。
number=input("Enter a number, and I'll tell you if it's even or odd:")
if int(number) %2==0:
????????print('\nThe number '+str(number)+' is even.')
else:
????????print('\nThe number '+str(number)+' is odd.')
2)while循環(huán)
current_number=1
while current_number<=5:
????????print(current_number)
????????current_number+=1
●??讓用戶選擇何時退出
prompt='Tell me something, and i will repeat it back to you'
prompt+='\nEnter quit to end the program.'
message=''
while message!='quit':
????????message=input(prompt)
????????if message!='quit':
????????????????print(message)
●??使用標志
在要求很多條件都滿足才繼續(xù)運行的程序中, 可定義一個變量, 用于判斷整個程序是否處于活動狀態(tài)。 這個變量被稱為標志,可讓程序在標志為True 時繼續(xù)運行, 并在任何事件導致標志的值為False 時讓程序停止運行。
prompt='Tell me something, and i will repeat it back to you'
prompt+='\nEnter quit to end the program.'
active=True
while active:
????????message=input(prompt)
????????if message=='quit':
????????????????active=False
????????else:
????????????????print(message)
●??使用break退出循環(huán)
prompt='Tell me something, and i will repeat it back to you'
prompt+='\nEnter quit to end the program.'
while True:
????????message=input(prompt)
????????if message=='quit':
????????????????break
????????else:
????????????????print(message)
●??在循環(huán)中使用continue
current_number=0
while current_number<=10:
????????current_number+=1
????????if current_number%2==0:
????????????????continue
????????print(current_number)
要返回到循環(huán)開頭, 并根據(jù)條件測試結果決定是否繼續(xù)執(zhí)行循環(huán), 可使用continue 語句
3)使用while循環(huán)來處理列表和字典
●??在列表之間移動元素
unconfirmed_users=['alice','brain','candy']
confirmed_users=[]
while unconfirmed_users:
????????current_user=unconfirmed_users.pop()
????????print('Veryfying user: '+current_user.title())
????????confirmed_users.append(current_user)
print('\nThe follwing users have been confirmed:')
for confirmed_user in confirmed_users:
????????print(confirmed_user.title())
●??刪除包含特定元素的所有列表元素
pet=['cat','dog','goldfish','dog','cat']
print(pet)
while 'cat' in pet:
????????pet.remove('cat')
print(pet)
●??由用戶輸入來填充字典
responses={}
polling_active=True
while polling_active:
????????name=input('\nWhat is your name? ')
????????response=input('\nWhich mountain would you like to climb someday?')
????????responses[name]=response
????????repeat=input('\nWould you like to let another person respond?(yes/no)')
????????if repeat=='no':
????????????????polling_active=False
print('\n---Poll Results---')
for name,response in responses.items():
????????print(name+' would like climb '+response+'.')
8、函數(shù)
1)定義函數(shù)
def? 定義以冒號結尾
def greet_user(user_name):
????????print('Hello, '+user_name.title()+'!')
greet_user('jesse')
●??實參和形參
變量user_name是一個形參 ——函數(shù)完成其工作所需的一項信息。 在代碼greet_user('jesse') 中,值'jesse' 是一個實參 。 實參是調用函數(shù)時傳遞給函數(shù)的信息。
2)傳遞實參
●??位置實參
要求實參的順序與形參的順序相同
def describe_pet(pet_type,pet_name):
????????print('\nI have a '+pet_type+'.')
????????print('My '+pet_type+"'s name is "+pet_name.title())
describe_pet('hamster','Henrry')
●??關鍵詞實參
每個實參都由變量名和值組成,直接在實參中將名稱和值關聯(lián)起來了
def describe_pet(pet_type,pet_name):
????????print('\nI have a '+pet_type+'.')
????????print('My '+pet_type+"'s name is "+pet_name.title())
describe_pet(pet_type='hamster',pet_name='Henrry')
●??默認值
編寫函數(shù)時, 可給每個形參指定默認值 。 在調用函數(shù)中給形參提供了實參時, Python將使用指定的實參值; 否則, 將使用形參的默認值。
def describe_pet(pet_type=‘dog',pet_name):
????????print('\nI have a '+pet_type+'.')
????????print('My '+pet_type+"'s name is "+pet_name.title())
describe_pet('Henrry')
3)返回值
函數(shù)返回的值被稱為返回值,可使用return語句將值返回到調用函數(shù)的代碼行。
●??返回簡單值
def get_formatted_name(first_name,last_name,middle_name=''):
????????if middle_name:
????????????????full_name=first_name+' '+middle_name+' '+last_name
????????else:
????????????????full_name=first_name+' '+last_name
????????return full_name.title()
musician=get_formatted_name('jimi','hendrix')
print(musician)
musician=get_formatted_name('john','hooker','lee')
print(musician)
●??返回字典
def person_name(first_name,last_name):
????????person={'first':first_name,'last':last_name}
????????return person
musician=person_name('jimi','hendrix')
print(musician)
4)傳遞列表
def person_name(names):
????????for name in names:
????????????????msg='Hello '+name.title()+'!'
????????print(msg)
usernames=['jimi','hendrix','john']
person_name(usernames)
●??在函數(shù)中修改列表
在函數(shù)中對這個列表所做的任何修改都是永久性的
unprinted_designs=['iphone case','robot pendant','dodecahedron']
complete_models=[]
while unprinted_designs:
????????current_design=unprinted_designs.pop()
????????print('Printing model:' + current_design)
????????complete_models.append(current_design)
print('\nThe following models have been printed:')
for complete_model in complete_models:
????????print(complete_model)
可編寫兩個函數(shù)重新組織這些代碼,效率更高。
def print_models(unprinted_designs,completed_models):
????????while unprinted_designs:
????????????????current_design=unprinted_designs.pop()
????????????????print('Printing model:' + current_design)
????????????????completed_models.append(current_design)
def show_compeled_models(completed_models):
????????print('\nThe following models have been printed:')
????????for completed_model in completed_models:
????????????????print(completed_model)
unprinted_designs=['iphone case','robot pendant','dodecahedron']
completed_models=[]
print_models(unprinted_designs,completed_models)
show_compeled_models(completed_models)
5)傳遞任意數(shù)量的實參
Python允許函數(shù)從調用語句中收集任意數(shù)量的實參,星號* 讓Python創(chuàng)建一個名為toppings 的空元組, 并將收到的所有值都封裝到這個元組中。
def make_pizza(*toppings):
????????print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
●??結合使用位置實參和任意數(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(13,'mushrooms', 'green peppers', 'extra cheese')
●??使用任意數(shù)量的關鍵字實參
**user_info 中的兩個星號讓Python創(chuàng)建一個名為user_info 的空字典, 并將收到的所有名稱—值對都封裝到這個字典中。
def build_profile(first,last,**user_info):
????????profile={}
????????profile['first_name']=first
????????profile['last_name']=last
????????for key,value in user_info.items():
????????????????profile[key]=value
????????????????return profile
user_profile=build_profile('albert','einstein',
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? location='princetion',
????????????????????????????????????????????????????? field='physics')
print(user_profile)
5)將函數(shù)存儲在模塊中
將函數(shù)存儲在被稱為模塊 的獨立文件中,再將模塊導入 到主程序中。import 語句允許在當前運行的程序文件中使用模塊中的代碼。模塊 是擴展名為.py的文件, 包含要導入到程序中的代碼。
●??導入整個模塊
def make_pizza(size,*toppings):
????????print('\nMaking a '+str(size)+'-inch pizza with the following toppings:')
????????for topping in toppings:
????????????????print('- '+topping)
●??將上述內容保存為pizza.py文件,再使用下面的調用語句
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
●??導入特定的函數(shù)
from module_name import function_0, function_1, function_2
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese'
●??使用as 給函數(shù)指定別名
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
●??使用as 給模塊指定別名
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
●??導入模塊中的所有函數(shù)
使用星號(* ) 運算符可讓Python導入模塊中的所有函數(shù)
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
9、類
1)創(chuàng)建和使用類
在Python中,創(chuàng)建類以class開頭,首字母大寫的名稱指的是類,小寫的名稱指根據(jù)類創(chuàng)建的實例。
●??創(chuàng)建Dog類
class Dog():
????????def __init__(self,name,age):
????????????????self.name=name
????????????????self.age=age
? ? ? ? def sit(self):
????????????????print(self.name.title()+' is now sitting.')
????????def roll_over(self):
????????????????print(self.name.title()+' rolled over!')
!注意!init左右兩邊有兩個_,方法__init__() 定義成了包含三個形參: self 、 name 和age 。 在這個方法的定義中, 形參self 必不可少, 還必須位于其他形參的前面。每個與類相關聯(lián)的方法調用都自動傳遞實參self , 它是一個指向實例本身的引用, 讓實例能夠訪問類中的屬性和方法。
●??根據(jù)類創(chuàng)建實例
my_dog = Dog('willie',6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
2)使用類和實例
●??Car類
class Car():
????????def __init__(self,make,model,year):
????????????????self.make=make
????????????????self.model=model
????????????????self.year=year
????????def get_descriptive_name(self):
????????????????long_name=str(self.year)+' '+self.make+' '+self.model
????????????????return long_name.title()
my_new_car=Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())
●??給屬性指定默認值
class Car():
????????def __init__(self,make,model,year):
????????????????self.make=make
????????????????self.model=model
????????????????self.year=year
? ? ? ? ? ? ? ? ?self.odometer_reading = 0
????????def get_descriptive_name(self):
????????????????long_name=str(self.year)+' '+self.make+' '+self.model
????????????????return long_name.title()
? ? ? ? def read_odometer(self):
????????????????print(‘This car has ’+str(self.odometer_reading)+'miles on it.')
my_new_car=Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
●??修改屬性的值
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
3)繼承
如果你要編寫的類是另一個現(xiàn)成類的特殊版本, 可使用繼承 。 一個類繼承 另一個類時, 它將自動獲得另一個類的所有屬性和方法; 原有的類稱為父類 , 而新類稱為子類 。 子類繼承了其父類的所有屬性和方法, 同時還可以定義自己的屬性和方法。定義子類時, 必須在括號內指定父類的名稱。super() 是一個特殊函數(shù), 幫助Python將父類和子類關聯(lián)起來。
●??子類的方法__init__()
class Car():
????????def __init__(self,make,model,year):
????????????????self.make=make
????????????????self.model=model
????????????????self.year=year
????????????????self.odometer_reading=0
????????def get_descriptive_name(self):
????????????????long_name=str(self.year)+' '+self.make+' '+self.model
????????????????return 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 = mileage
????????????????else:
????????????????????????print("You can't roll back an odometer!")
????????def increment_odometer(self, miles):
????????????????self.odometer_reading += miles
class ElectricCar(Car):
????????def __init__(self, make, model, year):
????????????????super().__init__(make, model, year)
????????????????self.battery_size = 70
????????def describe_battery(self):
????????????????print("This car has a " + str(self.battery_size) + "-kWh battery.")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_new_car.get_descriptive_name())
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()