《Python編程從入門到實踐》學習筆記

實際操作中給變量取的名字要可讀性強谋作,我這里給變量取的名字非常簡短毁靶,只是為了方便理解鞭铆。

第 1 章 起步

win+s 輸入cmd檢查python是否安裝成功, 或者win+s 辨赐,輸入IDLE也可以使用python(IDLE是Python自帶的)。

python文本編輯器:Geany京办,subline text掀序,vs code ,pycharm惭婿,jupyter notebook不恭。但是Geany,subline text在配置上很容易出現(xiàn)問題财饥,不建議使用换吧。

在vs code中運行.py文件

打開vs code——新建文件——文件另存為——某文件夾——保存類型選成:Python——在文件中輸入print("Hello world! My name is Shuntai Yu.")——調(diào)試——啟動調(diào)試——python file

在cmd中運行.py文件

cd 到.py文件所在位置——輸入.py文件名——enter

第 2 章 變量和簡單數(shù)據(jù)類型

在Python中, 用引號括起的都是字符串钥星, 其中的引號可以是單引號沾瓦, 也可以是雙引號

.title()、.upper()、.lower()贯莺、+风喇、\t,\n缕探、.rstrip()魂莫、.lstrip()、.strip()爹耗、str() 耙考、

修改大小寫

message="Hello! shuntai yu !"
print(message.title())   #使每個單詞首字母大寫
print(message.upper())   #所有字母都大寫
print(message.lower())   #所有字母都小寫

合并(拼接)

#合并(拼接) 字符串
first_name="shuntai"
last_name="yu"
full_name=first_name + " " + last_name
print("Hello" + " " + full_name.title() + " " + "!")   

添加空白和空白行

#制表符是\t,換行符是\n
print("python")
print("\npython")  #換行
print("\tpython")   #前面加一個空白

刪除空白

tmp="   python  "
print(tmp.rstrip())   #刪除尾空白
print(tmp.lstrip())   #刪除頭空白
print(tmp.strip())    #刪除兩端空白

非字符轉換成字符

# str() 它讓Python將非字符串值表示為字符串
age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)

python之禪

import this   #python之禪

第 3 章 列表簡介

Python 用[ ] 表示列表鲸沮, 并用逗號來分隔元素琳骡。索引從0開始。
.append()讼溺、.insert()楣号、del語句、.pop()怒坯、.remove()炫狱、.sort()、sorted()剔猿、.reverse()

提取元素

bicycles = ['trek', 'cannondale', 'redline', 'specialized','ducati']
print(bicycles[0])
print(bicycles[0].title())    #使首字母大寫
print(bicycles[-1])   #索引為-1 表示倒數(shù)第一個列表元素视译,為-2為倒數(shù)第二個,依此類推归敬。

更改酷含,添加元素

bicycles[0] = 'ducati'     #將第1個元素改成ducati
print(bicycles)
bicycles.append('zzz')    #末尾附加元素
bicycles.insert(0, 'iii')       #指定索引和值插入新元素

刪除元素

del bicycles[0]       #根據(jù)索引刪除
popped_bircycle = bicycles.pop()      #刪除最后一個元素
print(bicycles)
print(popped_bicycle)       #訪問被刪除的值
bicycles.pop(1)       #指定索引獲取任意元素
bicycles.remove('ducati')      #根據(jù)元素刪除

排序和確定元素個數(shù)

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()      #sort() 對列表進行永久性排序,變成cars.sort(reverse=True)則反向永久排序
print(cars)
print(sorted(cars))     #sorted() 對列表進行臨時排序汪茧,也可傳遞參數(shù)reverse=True
print(cars)
cars.reverse()    #永久反轉排列順序椅亚,使用兩次可回到原順序
print(cars)
len(cars)       #確定列表元素個數(shù)

第4 章 操作列表

for循環(huán)、range()舱污、enumerate()

tmp = [12,13,33,45,45,67,33,22,98]
foo = enumerate(tmp)   # enumerate可以獲取每個元素的索引和值
for id,bd in foo:
    print(id,bd)   #將會得到每個元素的索引和值

for循環(huán)

注意:縮進呀舔,冒號,[:]

foo = ['AAA', 'BBB', 'CCC']
for id in foo:    #所謂遍歷整個列表就是對列表中的每個元素執(zhí)行相同的操作
    print(id)

縮進

屬于循環(huán)部分的代碼要縮進扩灯,循環(huán)外部代碼不縮進

magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician.title() + ", that was a great trick!")
    print("I can't wait to see your next trick, " + magician.title() + ".\n")   #縮進則每循環(huán)一次就執(zhí)行一次媚赖,不縮進則只在循環(huán)結束時執(zhí)行一次。
for id in range(1,5):
    print(id)

for id in range(1,11,2):    #2為步長
    print(id)
foo = list(range(1,5))
print(foo)

數(shù)字列表創(chuàng)建珠插、運算惧磺、解析

foo = []   #創(chuàng)建空list
for id in range(1,11):
    arg = id**2
    foo.append(arg)     #要熟系.append的用法,foo.append(arg) 表示將arg的值追加到foo后面捻撑,for循環(huán)遍歷每一個值豺妓,對每一個值求平方惜互,將平方值追加到list里面。
print(foo)
sum(foo)   #求和琳拭,若是min或者max則為求最小值训堆,最大值

#與上同
tmp=[]
for id in range(1,11):
    tmp.append(id**2)   #可直接將平方追加到list
print(tmp)

#列表解析
foo=[id**2 for id in range(1,11)]
print(foo)

切片和復制列表

tmp = ['charles', 'martina', 'michael', 'florence', 'eli']
print(tmp[0:3])   #第1到第3個元素;[:3]也表示第1到第3個元素白嘁;[3:]表示第3到最后一個元素坑鱼;[-2:]表示最后兩個元素
foo=tmp[:]   #復制列表,此時foo是tmp的拷貝
print(foo)

foo=tmp   #這樣是不行的
print(foo)
tmp.append("AAA")
print(tmp)
print(foo)  #在tmp后面追加同樣會出現(xiàn)在foo里面絮缅,因為foo=tmp將兩個變量指向了同一個列

#通過for循環(huán)遍歷切片
for id in tmp[0:3]:
    print(id.title())

元組

不可變的列表稱為元組 鲁沥。雖然元組變量元素不能修改,但是可以給變量重新賦值耕魄。

tmp=(200,50)
print(tmp[0])  #通過索引號訪問元組元素
print(tmp[1])

tmp[0]=111   #會報錯画恰,因為元組元素不可更改

tmp=(111,50)    #給變量重新賦值
print(tmp)

第 5 章 if 語句

==、!=吸奴、>=允扇、<=、>则奥、<考润、and、or读处、

判斷比較和檢查

tmp=["audi","bmw","subaru","toyota"]
for id in tmp:
    if id=='audi':    #注意這里有冒號
        print(id.title())
    else:                #注意這里有冒號
        print(id.upper())

'audi' in tmp    #檢查某個值是否包含在列表中糊治,會返回TRUE和FALSE; 若是 'audi' not in tmp   則檢查某個值是否不包含在列表中

if 'aaa' not in tmp:
    print("不包含罚舱!")
car = 'bmw'
if car == 'bmw':   #通過==判斷是否相等井辜,!=判斷是否不等,
    print("干得好!")

檢查多個條件

使用and 和or檢查多個條件

age_0 = 22
age_1 = 18
age_0 >= 21 and age_1 >= 21    #等價于(age_0 >= 21) and (age_1 >= 21)管闷,加上括號提高可讀性

if-else

tmp=17
if tmp >=18:
    print("條件成立抑胎!")
else:    # 在 IDLE 里該句最靠左邊
    print("條件不成立!")

if-elif-else

tmp=27
if tmp <= 4:
    print("tmp不大于4")
elif tmp < 18:
    print("tmp介于4和18之間")
else:
    print("tmp大于等于18")

#可以有多個elif
age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:     # Python不要求if-elif 結構后面必須有else 代碼塊,故該句可改成elif age >=65: 
    price = 5
print("Your admission cost is $" + str(price) + ".")

for循環(huán)里用if 和 if里面用for循環(huán)

tmp = ['mushrooms', 'green peppers', 'extra cheese']
for id in tmp:
    if id == 'green peppers':
        print("Sorry, we are out of green peppers right now.")
    else:
        print("Adding " + id + ".")
print("\nFinished making your pizza!")

確定列表非空

在if 語句中將列表名用在條件表達式中時渐北, 列表非空時返回True ,空列表返回False铭拧。

tmp=[]
if tmp:     #因為tmp是空列表赃蛛,所以返回False,執(zhí)行else
    if 'aaa' in tmp:
        print("aaa在里面")
else:
    print("這他媽是個空的搀菩!")

確定一個列表中的元素是否存在于另一個列表

tmp = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
foo = ['mushrooms', 'french fries', 'extra cheese']
for id in foo:
    if id in tmp:
        print("Adding " + id + ".")
    else:
        print("Sorry, we don't have " + id + ".")
        print("\nFinished making your pizza!")

第6章 字典

列表是[]呕臂,元組是(),字典是{}

tmp = {'color': 'green', 'points': 5}    #字典中存儲的是鍵-值對肪跋,這個字典存儲了兩個鍵-值對歧蒋。
print(tmp['color'])
print(tmp['points'])

創(chuàng)建、填充、訪問谜洽、添加萝映、修改、刪除阐虚、遍歷

tmp = {}    #創(chuàng)建空字典
tmp['color'] = 'green'   #填充空字典序臂,[ ]里面是鍵,=右邊是值
tmp['points'] = 5
print(tmp)    # tmp = {'color': 'green', 'points': 5}

print(tmp['points'])  # 訪問字典中的值

tmp['bar'] = 0   #添加鍵-值對实束。鍵-值對在字典中的排列順序不重要奥秆,但是鍵和值的對應關系重要
print(tmp)

tmp['color'] = 'yellow'  #修改字典中的值
print(tmp)

del tmp['bar']  #刪除鍵值對
print(tmp)

#遍歷字典中所有鍵、值咸灿、鍵值對
for id,foo in tmp.items():    # for 鍵變量,值變量 in 字典.items():    ##遍歷鍵值對的方式构订。   
    print("\nid:" + id)
    print("foo:" + str(foo))  #若字典的值沒有數(shù)字,foo這里不需要寫str

for id in tmp.keys():    # 遍歷鍵是將items換成keys避矢;將tmp.keys()改成set(tmp.keys())可以去除重復悼瘾,將set換成sorted可以排序撮躁。
    print(id.title())

for id in tmp.values():    # 遍歷值是將items換成values
    print(str(id).title())  

嵌套

在列表中嵌套字典

alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for id in aliens:
    print(id)

在字典中嵌套列表

當需要在字典中將一個鍵關聯(lián)到多個值時赏壹, 可以在字典中嵌套一個列表抹剩。

alien = {'color': ['green', 'yellow', 'red'], 'points': [5,10,15]}   
for id in alien['color']:
  print(id)

在字典中嵌套字典

字典中嵌套字典要注意四個逗號羞延,結構是 {鍵:{鍵:值,},鍵:{鍵:值,},}

users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',    #注意這里的逗號
},    #注意這里的逗號
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',   #注意這里的逗號
},    #注意這里的逗號
}

for id,foo in users.items():
    print("\nUsername:" + " " +id)
    print("\tFull name:" + " " + foo['first'].title() + " " + foo['last'].title())
    print("\tLocation:" + " " + foo['location'].title())

第7章 用戶輸入和while 循環(huán)

input()

函數(shù)input() 可暫停程序砰诵,顯示input()中的提示栗柒,等待用戶輸入徒溪。 可將用戶輸入存儲在一個變量中梳侨,然后使用輸入尺上。

>>> id = input("Tell me your name: ")    #等待用戶輸入文本材蛛,將其存儲在變量中。
Tell me your name:Shuntai Yu
>>> print(id + " " + "is very hansome!")    #使用輸入
Shuntai Yu is very hansome!

同上
>>> tmp = "Tell me your name: "
>>> id = input(tmp)
Tell me your name: Shuntai Yu
>>> print(id + " " + "is very hansome!")
Shuntai Yu is very hansome!

#在提示中添加內(nèi)容
>>> tmp = "Tell me your name"
>>> tmp += ",please! :"   # +=可以在提示中添加新的內(nèi)容怎抛。
>>> id = input(tmp)
Tell me your name,please! :Shuntai Yu
>>> print(id + " " + "is very hansome!")
Shuntai Yu is very hansome!

int()

python會將用戶輸入看做字符串卑吭,使用int()可以獲得數(shù)值

>>> age = input("How old are you? ")
How old are you? 21   
>>> age >= 18     #上面輸入的數(shù)字會被認作字符串,所以這里會報錯
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'str' and 'int'
>>> age = int(age)    #轉成數(shù)值
>>> age >= 18    #數(shù)值可以進行判斷
True

%

%將兩個數(shù)相除并返回余數(shù):

>>> 4 % 3
1

while循環(huán)

一個思想很重要:while就是判斷马绝,若為邏輯運算則while后面的為True豆赏,就繼續(xù)執(zhí)行;若后面是列表字之類的富稻,則非空就繼續(xù)執(zhí)行掷邦。所以while id就是判斷id的邏輯值。

>>> id = 1
>>> while id <= 5:   #while就是判斷椭赋,while后面的為id <= 5抚岗,若為True就繼續(xù)執(zhí)行
...     print(id)   # 我是用的IDLE,注意該句前面tab鍵
...     id += 1    #該句等于 id = id + 1
...
1
2
3
4
5
>>> id = True
>>> while id:    # #while就是判斷哪怔,while后面的為id宣蔚,而id = True向抢,所以會繼續(xù)執(zhí)行下面的代碼。
    print("Hello!")
        break    #若此處不break胚委,則會產(chǎn)生無限循環(huán)挟鸠。
#該例子沒有停止運行while循環(huán),所以會不停執(zhí)行下去篷扩。終止它使用Ctrl + C兄猩。
id = False
while id ==False:
    print("Hello!")

    
Hello!
Hello!
Hello!
  .
  .
  .
tmp = ['a', 'b', 'c']
while tmp:   # tmp為非空列表,故后面可以繼續(xù)執(zhí)行鉴未。
    print('hello')
    break

讓用戶選擇何時退出

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "    # 我的理解:這個+=可以理解為對上面定義的補充枢冤,因為上面已經(jīng)對prompt進行了定義,這里表示再對定義進行追加內(nèi)容铜秆。
message = ""  
while message != 'quit':  #若無可供比較的東西淹真,程序無法繼續(xù)運行,所以上面給message賦了空字符串连茧。 
    message = input(prompt)
    print(message)

#如果沒有可供比較的東西核蘸, Python將無法繼續(xù)運行程序。 為解決這個問題啸驯, 我們必須給變量message 指定一個初始值客扎。 雖然這個初始值只是一個空字符串, 但符合要求罚斗, 讓Python能夠執(zhí)行while 循環(huán)所需的比較徙鱼。 只要message 的值不是'quit' , 這個循環(huán)就不斷運行针姿。首次遇到該循環(huán)時袱吆,message 是空字符串, 因此進入循環(huán)距淫。 

#下面這個也可以實現(xiàn)上面的效果
tmp = "\nTell me something, and I will repeat it back to you:"
tmp += "\nEnter 'quit' to end the program."
id = ''
while id != 'quit':
    id=input(tmp)

#下面這個也可以實現(xiàn)上面的效果
tmp='\nTell me something, and I will repeat it back to you:'
foo="Enter 'quit' to end the program."
id=''
while id !='quit':
    print(tmp)
    id=input(foo)

#比較一下這三種實現(xiàn)方法绞绒。

標志

標志是程序的交通信號燈。 可以讓程序在標志為True 時繼續(xù)運行(當然也可以為False時繼續(xù)運行榕暇,自己設置)蓬衡,這樣, 在while 語句中只需檢查標志的當前值是否為True 彤枢,并將所有測試都放在其他地方狰晚, 從而讓程序更整潔。

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
id = True
while id:
    message = input(prompt)
    if message == 'quit':
        id = False
    else:
        print(message)

break 和 continue

break不再執(zhí)行余下的代碼堂污,直接跳出循環(huán)。
continue忽略余下的代碼龄砰,返回到循環(huán)開頭盟猖。

>>> id = True
>>> while id:    #以while True 打頭的循環(huán)將不斷運行讨衣, 直到遇到break 語句。 
    print("Hello!")
        break
    
Hello!
#從1數(shù)到10只打印奇數(shù)
id = 0
while id < 10:
    id += 1
    if id % 2 == 0:
        continue   # continue忽略剩下的代碼式镐,返回到循環(huán)開頭反镇。
        
    print(id)

使用while 循環(huán)來處理列表和字典

列表之間移動元素

只是遍歷列表可使用for循環(huán)while循環(huán)
在遍歷列表的同時又要對其進行修改娘汞,使用while 循環(huán)歹茶,不能用for循環(huán)。 通過將while 循環(huán)同列表和字典結合起來使用你弦, 可收集惊豺、 存儲并組織大量輸入, 供以后查看和顯示禽作。

親手打一下下面的例子尸昧!

# 首先,分別創(chuàng)建一個非空列表和空列表旷偿,將非空列表中處理后的元素移到空列表中烹俗。
tmp = ['alice', 'brian', 'candace']
foo = []

# 處理tmp中每個元素,并將處理過的元素移到foo中
while tmp:
    arg = tmp.pop()
    print("Verifying user: " + arg.title())   #這里的處理就是首寫字母變成大寫
    foo.append(arg)

# 顯示處理過的元素
print("\nconfirmed users:")
for arg in foo:
    print(arg.title())
pets = ['cat','cat','cat','dog','dog','dog','rabbit']
print(pets)
pets.remove('cat')   # .remove() 只能一次刪除一個萍程,想將pets里面的‘cat’全部刪除需要使用循環(huán)幢妄。
print(pets)

while 'cat' in pets:   # 使用循環(huán)可全部刪除
    pets.remove('cat')
print(pets)

使用用戶輸入填充字典

實現(xiàn)如下
What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/ no) yes
What is your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond? (yes/ no) no
--- Poll Results ---
Lynn would like to climb Devil's Thumb.
Eric would like to climb Denali.

方法一:

responses = {}
polling_active = True  # 設置一個標志, 指出調(diào)查是否繼續(xù)
while polling_active:
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb someday? ")
    responses[name] = response  # 將用戶輸入填充進字典
    repeat = input("Would you like to let another person respond? (yes/ no) ")
   
    if repeat == 'no':   # 通過if來實現(xiàn)以用戶輸入來決定是否結束while循環(huán)
        polling_active = False   

print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name + " would like to climb " + response + ".")

方法二:

tmp = {}
name = input("what is your name? ")
mou = input("which mountain would you like to climb someday? ")
tmp[name] = mou
foo = input("Would you like to let another person respond? (yes/ no) ")
while foo =='yes':
    name = input("what is your name? ")
    mou = input("which mountain would you like to climb someday? ")
    tmp[name] = mou
    foo = input("Would you like to let another person respond? (yes/ no) ")

print("\n---poll results---")
for id,arg in tmp.items():
    print(id + " would like to climb " + arg)

第8章 函數(shù)

定義函數(shù)

定義函數(shù)使用def茫负,def是指definition的縮寫

def 函數(shù)名(形參):     #即使沒有形參蕉鸳,()也不可少; 若多個形參朽褪,則用,間隔置吓;
  函數(shù)要執(zhí)行的任務
def funct(id,fib,arg="rabbit"):    # id和fib和arg是三個形參,即函數(shù)完成工作所需要的信息缔赠。并且形參可以指定默認值衍锚,arg就指定了默認值。
    print("\nI have a " + id + ".")
    print("My " + id + "'s name is " + fib.title() + ".")
    print("My " + arg + "'s name is Jack .")

funct('dog', 'Lily')   #  'dog'和 'Lily'是實參嗤堰,即調(diào)用函數(shù)時傳遞給函數(shù)的信息戴质,這種是位置實參,要求順序和形參一致踢匣。arg沒有新賦值告匠,則使用默認值。
funct('dog', 'Lily','cat')   #arg新賦值為'cat'所以棄默認值离唬,使用新賦值后专。
funct(fib = 'Lily',id = 'dog', arg="cat")   #這種是關鍵字實參,因為指定了形參名输莺,所以不需要順序一致戚哎。且對arg賦了新值裸诽,故使用新值。

# 位置實參型凳、關鍵字實參和默認值可以混合使用

返回值

def funct(id,foo):
    arg = id + ' ' + foo
    return arg.title()    # 函數(shù)中使用return將值返回到函數(shù)調(diào)用行

fib = funct('shuntai', 'yu')    # 存儲返回值需要提供變量
print(fib)


#函數(shù)可返回任何類型的值
def funct(first_name, last_name):
    person = {'first': first_name, 'last': last_name}
    return person    #返回的是字典
musician = funct('jimi', 'hendrix')
print(musician)

讓實參變成可選

def funct(first_name, middle_name, last_name):
    full_name = first_name + ' ' + middle_name + ' ' + last_name
    return full_name.title()

musician = funct('john', 'lee', 'hooker')
print(musician)

上面的例子適用于有中間名的名字丈冬,但不是所有人都有中間名,所以要讓中間名的實參變得可選

def funct(first_name, last_name, middle_name=''):   #先將中間名變成空字符串
    if middle_name:     # 進行判斷甘畅,若中間名非空埂蕊,后續(xù)執(zhí)行;若中間名為空則執(zhí)行else疏唾。
        full_name = first_name + ' ' + middle_name + ' ' + last_name
    else:
        full_name = first_name + ' ' + last_name
    return full_name.title()
musician = funct('jimi', 'hendrix')
print(musician)
musician = funct('john', 'hooker', 'lee')
print(musician)

結合使用函數(shù)和while循環(huán)

實現(xiàn)如下效果:
Please tell me your name:
enter 'q' at any time to quit
First name: eric
Last name: matthes

Hello, Eric Matthes

Please tell me your name:
enter 'q' at any time to quit
First name: q

方法1:

def funct(First_name,Last_name):
    tmp = "\n" + "Hello, " + First_name + " " + Last_name + "!\n"
    return tmp.title()

while True:
    print("Please tell me your name:")
    print("(" + "enter 'q' at any time to quit" + ")")
    f_name = input("First name: ")
    if f_name == 'q':
        break
    l_name = input("Last name: ")
    if l_name == 'q':
        break
    foo = funct(f_name,l_name)
    print(foo)

方法2:

def funct(first_name,last_name):
    print("\nHello, " + f_name.title() + " " + l_name.title() + "!\n")

while True:
    print("Please tell me your name:")
    print("(" + "enter 'q' at any time to quit" + ")" )
    f_name = input("First name: ")
    if f_name =='q':
        break
        
    l_name = input("Last name: ")
    if l_name =='q':
        break
        
    funct(f_name,l_name)

第7章 使用while 循環(huán)來處理列表和字典 那一個例子可以定義兩個函數(shù)

tmp = ['alice', 'brian', 'candace']
foo = []

def funct_1(tmp,foo):    #定義第一個函數(shù)
    while tmp:
        arg = tmp.pop()
        print("Verifying user: " + arg.title())   #這里的處理就是首寫字母變成大寫
        foo.append(arg)

def funct_2(foo):    #定義第二個函數(shù)
    print("\nconfirmed users:")
    for arg in foo:
        print(arg.title())
        
funct_1(tmp,foo)    # 這個函數(shù)運行之后蓄氧,tmp會變成空列表,若不想如此荸实,則可以用tmp[:]替換tmp匀们,即用tmp的副本作為函數(shù)的實參。
funct_2(foo)

print(tmp)  # 可以看到tmp變空了
print(foo)   #可以看到foo變滿了

傳遞任意數(shù)量的實參

一個 * 創(chuàng)建空元組准给,兩個 * 創(chuàng)建空字典泄朴。

空元組

在形參名前面加 * 可以創(chuàng)建一個空元組,該空元組可以將接收到的所有值都封裝到這個元組中露氮。

def funct(*foo):
    print(foo)
    
funct('aaa')
funct('aaa', 'bbb', 'ccc')

當函數(shù)接受不同類型的實參祖灰,則星號實參要放在最后。python會先匹配位置實參和關鍵字實參畔规,再將剩下的實參都收集進最后一個形參中局扶。

def funct(size,*foo):
    print("Making a " + str(size) + "-inch pizza with the following topppings:")     # 數(shù)字要通過str() 轉換
    for id in foo:
        print("-" + id)

funct(2,'aaa')
funct(5,'aaa', 'bbb', 'ccc')   #先匹配位置實參5,再將剩下的實參都收集進最后一個形參中叁扫。

空字典

有時候三妈, 需要接受任意數(shù)量的實參, 但預先不知道傳遞給函數(shù)的會是什么樣的信息莫绣。 在這種情況下畴蒲, 可創(chuàng)建空字典。

def build_profile(first, last, **user_info):    # 兩個星號創(chuàng)建一個名為user_info 的空字典对室, 并將收到的所有名稱—值對都封裝到這個字典中模燥。 

#創(chuàng)建字典并將非星實參填充進字典    
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    
    for key, value in user_info.items():   #遍歷星號實參鍵-值對
        profile[key] = value    # 也填充進同一字典
    return profile    #將非星實參和星號實參填充好的字典返回給函數(shù)調(diào)用行

user_profile = build_profile('albert', 'einstein',
                             location='princeton',
                             field='physics')
print(user_profile)

#調(diào)用這個函數(shù)時, 不管額外提供了多少個鍵—值對掩宜, 它都能正確地處理蔫骂。

將函數(shù)存儲在模塊

類似于shell中的創(chuàng)建函數(shù)庫。只需編寫一條import 語句并在其中指定模塊名牺汤, 就可在程序中使用該模塊中的所有函數(shù)辽旋。

例子1

下面這個例子使用jupyter無法展示,可用vs code。

創(chuàng)建模塊

創(chuàng)建一個 .py 為后綴的文件补胚,可在該文件中定義很多函數(shù)固该,該文件稱為模塊
pizza.py

def funct(size, *toppings):
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

讀取模塊

讀取模塊則調(diào)用函數(shù)時需要帶上模塊名,讀取模塊中函數(shù)則調(diào)用函數(shù)時不需要帶上模塊名糖儡。

pizza.py文件同一目錄下新建making_pizzas.py文件

讀取所有函數(shù)

making_pizzas.py

import pizza   # 讀取模塊,此時模塊中所有函數(shù)都可調(diào)用怔匣。讀取方法:  import 模塊名
#import pizza as pp   # 可以給模塊指定別名握联,若這里指定別名,下面也要改

pizza.funct(16, 'pepperoni')   # 調(diào)用模塊中的函數(shù)每瞒,需要帶上模塊名金闽,方法:  模塊名.函數(shù)名() 
pizza.funct(12, 'mushrooms', 'green peppers', 'extra cheese')
讀取特定函數(shù)
from pizza import funct    # 讀取模塊中特定函數(shù)
from pizza import *    # 讀取模塊中所有函數(shù),下面調(diào)用函數(shù)時也不用帶上模塊名剿骨。但這種方法極不推薦代芜,可能會導致災難性后果。
#from pizza import funct as tmp    # 當函數(shù)名太長或者與當前程序中的一些變量名沖突時則使用as為函數(shù)指定別名浓利,這里指定funct的別名為tmp

funct(16, 'pepperoni')   # 調(diào)用模塊中的函數(shù)不需要帶上模塊名挤庇,方法:  模塊名.函數(shù)名()    #若上面為別名,這里也要為別名
funct(12, 'mushrooms', 'green peppers', 'extra cheese')

第9章 類

編寫類時贷掖, 定義一大類對象都有的通用行為嫡秕。 基于類創(chuàng)建對象時, 每個對象都自動具備這種通用行為苹威, 然后可根據(jù)需要賦予每個對象獨特的個性昆咽。 根據(jù)類來創(chuàng)建對象被稱為實例化,這讓你可以使用類的實例牙甫。

9.1創(chuàng)建和使用類

#創(chuàng)建一個表示小狗的類Dog (它表示的不是特定的小狗掷酗,而是小狗這一類)
# Dog類包含 名字和年齡 + 蹲下和打滾。
#然后通過編寫好的類去創(chuàng)建特定小狗的實例窟哺。
#創(chuàng)建Dog實例時泻轰,通過實參向Dog()傳遞名字和年齡,self會自動傳遞脏答。
#類中的函數(shù)稱為方法

class Dog():    # 定義類: class 類名(首字母大寫)():

    def __init__(self, name, age):   #定義名字和年齡糕殉。 注意init開頭和末尾各兩個下劃線。 形參self一定要有殖告,并且要在其它形參前面阿蝶。  __init__接受形參的值,并將它們存儲在根據(jù)該類創(chuàng)建的實例屬性中黄绩。
        self.name = name    # (鄙人愚見:通過添加self前綴將對應的實參加進屬性羡洁,這里可以改成self.tmp = name,但是后面使用self.name的地方要對應為self.tmp爽丹,對應的都是形參name筑煮,只不過在屬性中一個命名為了name辛蚊,一個命名為了tmp,類中其它方法使用時后續(xù)調(diào)用)真仲。以self為前綴的變量可以供類中所有方法使用袋马。 這一步目的是獲取存儲在形參name中的值,并將其存儲到變量name中秸应,然后該變量被關聯(lián)到當前創(chuàng)建的實例虑凛。
        self.age = age    #也可改成 self.foo = age,但是后續(xù)調(diào)用時要使用self.foo而不能再使用self.age

    def sit(self):     #定義蹲下软啼,只有形參self桑谍,則后面創(chuàng)建的實例都能訪問該方法
        print(self.name.title() + " is now sitting.")

    def roll_over(self):     #定義打滾
        print(self.name.title() + " rolled over!")
            
        
#創(chuàng)建實例

#訪問屬性和調(diào)用方法的辦法就是: 實例名.屬性名/方法名()

## 訪問屬性
### 訪問屬性的辦法:  實例名.屬性名
my_dog = Dog('willie',6)  # 使用前面編寫好的Dog類創(chuàng)建實例,取名為my_dog祸挪;讓python創(chuàng)建一個名字為Willie锣披,年齡為6的小狗,self不需要給
print("My dog's name is " + my_dog.name.title() + ".")    #句點法訪問屬性
print("My dog is " + str(my_dog.age) + " years old.")

your_dog = Dog('lucy', 3)  #可以創(chuàng)建多個實例贿条,這是另一個實例
print("\nYour dog's name is " + your_dog.name.title() + ".")
print("Your dog is " + str(your_dog.age) + " years old.")     


## 調(diào)用方法(使用句點法調(diào)用類中定義的任何方法(函數(shù)))
### 調(diào)用方法的辦法:  實例名.方法名
my_dog.sit()
my_dog.roll_over()

your_dog.sit()
your_dog.roll_over()   

9.2使用類和實例


class Car():

    def __init__(self, make, model, year):    #方法__init__() 接受這些形參的值雹仿, 并將它們存儲在根據(jù)這個類創(chuàng)建的實例的屬性中。 
        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):   
        """打印一條指出汽車里程的消息"""    #函數(shù)中兩個雙引號引起來,是注釋悄蕾,不會執(zhí)行票顾。
        print("This car has " + str(self.odometer_reading) + " miles on it.") 

#################################### 代碼1 #######################################

#以上部分代碼簡稱 代碼1,下面會用到帆调。

                
my_new_car = Car('audi', 'a4', 2016)   #創(chuàng)建實例 my_new_car奠骄; 給出三個實參,self不用給番刊。
print(my_new_car.get_descriptive_name())   #訪問屬性

my_new_car.read_odometer()    #調(diào)用方法

9.2.3修改屬性的值

直接修改

# 代碼1
my_new_car.odometer_reading = 23
my_new_car.read_odometer()

通過方法修改

(即通過定義新的函數(shù)修改)

# 代碼1             
    def update_odometer(self, mileage):
        self.odometer_reading = mileage   # 此處直接接受參數(shù)
        
my_new_car = Car('audi', 'a4', 2016)         
my_new_car.update_odometer(23)    # 通過向新定義的方法 update_odometer傳遞參數(shù)來修改
my_new_car.read_odometer()

# 通過在方法 update_odometer 里面添加 if 來禁止往回調(diào)里程表讀數(shù)
# 代碼1             
    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:   #前面是直接接收參數(shù)含鳞,這里改一下,使接收時進行一下判斷芹务。
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
        
my_new_car = Car('audi', 'a4', 2016)         
my_new_car.update_odometer(23)
my_new_car.read_odometer()

9.3 繼承

繼承五步驟:
1)括號中指定父類名稱
2)初始化父類屬性
3)super()關聯(lián)父子
4)添加新屬性
5)添加描述新屬性的方法

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):  #步驟1:括號中指定父類名稱     
    def __init__(self, make, model, year):  #步驟2:初始化父類屬性  
        super().__init__(make, model, year)  #步驟3:super()關聯(lián)父子
        self.battery_size = 70    #步驟4:添加新屬性
   
    def describe_battery(self): #步驟5:添加描述新屬性的方法
        print("This car has a " + str(self.battery_size) + "-kWh battery.")

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()

9.3.4重寫父類的方法 和 9.3.5將實例用作屬性看書

第10章 文件和異常

讀取文件

文件名為 pi_digits.txt蝉绷,文件的保存路徑為D:\python_work\text_files,文件內(nèi)容如下

3.1415926535
8979323846
2643383279

file_path = 'D:/python_work/text_files/pi_digits.txt'    #指定絕對路徑枣抱,但是要將\換成/
with open(file_path) as file_object:    # with open as結構熔吗; with可以在不需要訪問文件后將其關閉; open(文件名) 可以打開文件
    contents = file_object.read()    # 方法read()讀取該文件全部內(nèi)容并存儲在contents中
    print(contents.rstrip())    #打印佳晶。 不加 .rstrip()發(fā)現(xiàn)會有一個空行桅狠,加了之后可以刪除字符串末尾的空白

#open()是函數(shù),read()是方法。

遍歷

file_path = 'D:/python_work/text_files/pi_digits.txt'
with open(file_path) as file_object:    
    for id in file_object:
        print(id.rstrip())    # 如果是用print(id)則每一行下會有一個空行中跌,用.rstrip()可以去除空行咨堤。


# 同上
file_path = 'D:/python_work/text_files/pi_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()
    for id in lines:
        print(id.rstrip())    
file_path = 'D:/python_work/text_files/pi_digits.txt'

with open(file_path) as file_object:
    lines = file_object.readlines()
    pi_string = ''

    for id in lines:
        pi_string += id.rstrip()

    print(pi_string)
    print(pi_string[:9] + "...")    # 指定顯示的字符數(shù)
    print(len(pi_string))

tmp = input("Please enter your number: ")
if tmp in pi_string:
    print("Yes!")
else:
    print("No!")

寫入文件

tmp = "programming.txt"

with open(tmp, 'w') as id:    # open有3個實參,r(讀取)漩符、w(寫入)一喘、a(附加);若省略實參嗜暴,則默認為讀取津滞。換成r和a試一下,以w模式打開文件一定小心,若文件本身有內(nèi)容灼伤,則會被清空。
    id.write("I love programming.\n")   # 換行符可以換行
    id.write("I love creating new games.")    # 寫入多句則多次使用 .write()

異常

print(5/0)  # 會發(fā)生報錯咪鲜,顯示Traceback

使用try-except狐赡,當try無異常則執(zhí)行try下的,跳過except疟丙;若異常與except后的異常匹配颖侄,則繼續(xù)運行

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divyexcee by zero!")

實現(xiàn)如下效果:
Give me two numbers, and I'll divide them.
Enter 'q' to quit.
First number: 5
Second number: 0
You can't divide by 0!
First number: 5
Second number: 2
2.5
First number: q

print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("Second number: ")
    try:
        answer = int(first_number) / int(second_number)    # 可能引發(fā)異常的代碼放try里面
    except ZeroDivisionError:    #except 代碼塊告訴Python, 如果它嘗試運行try 代碼塊中的代碼時引發(fā)了指定的異常享郊, 該怎么辦览祖。
        print("You can't divide by 0!")
    else:    # 若try代碼成功執(zhí)行,則執(zhí)行else
        print(answer)

# 下面這個是錯的炊琉,想想錯在哪里了展蒂?很有趣!
print("Give me two numcers, and I'll divide them.")
print("Enter 'q' to quit.")

while True:
    f_number = input("First number: ")
    if f_number == 'q':
        break

    s_number = input("Second number: ")


    answer = int(f_number)/int(s_number)
    try:
        print(answer)
    except ZeroDivisionError:
        print("You can't divide by 0!")

#可能引發(fā)異常的代碼才需要放在try語句中 answer = int(first_number) / int(second_number)可能異常

文本統(tǒng)計字數(shù)

def funct(file_name):
    try:
        with open(file_name, 'r') as tmp:   # with open as結構
            foo = tmp.read()    # 方法read()讀取該文件全部內(nèi)容并存儲在foo中
    except FileNotFoundError:
        print(file_name + " does not exist!")    # 若這里改成 pass 則失敗時一聲不吭苔咪,不顯示任何消息锰悼。
    else:    
        fib = foo.split()    # split()以空格為分隔符將字符串拆分,并存儲進一個列表
        num_words = len(fib)
        print("The file " + file_name + " has about " + str(num_words) + " words.")

filename = ["pi_digits.txt","pi_million_didits.txt","programming.txt"]    # 通過for循環(huán)遍歷文件名
for id in filename:
    funct(id)

10.4 存儲數(shù)據(jù)

json.dump() 和 json.load()

三步驟

  1. 導模
  2. with open as
  3. json.dump() / json.load() 团赏。json.dump() 接受兩個實參箕般,要被存儲的數(shù)據(jù)和可用于存儲的文件對象,json.load()接受一個實參舔清,即要讀取的對象丝里。注意一點,不管是dump還是load都需要的是對象体谒!也就是as后面那個東西杯聚,別寫錯了。

json.dump()是進行存儲

import json    #導入模塊json
numbers = [2, 3, 5, 7, 11, 13]

#filename = 'tmp.json'    # tmp.json只是隨便取的名字

with open('tmp.json', 'w') as foo:    # 以w模式打開tmp.json文件(json此時可以將數(shù)據(jù)寫入抒痒, tmp.json只是隨便取的名字)械媒,然后生成一個可用于存儲數(shù)據(jù)的文件對象,并將該對象取名為 foo
    json.dump(numbers,foo)    # json.dump() 將numbers寫入foo中

**json.load() **是進行讀取

import json

with open('tmp.json','r') as foo:   # 以r模式打開tmp.json文件
    arg = json.load(foo)    #不管是dump還是load都需要的是對象!也就是as后面那個東西纷捞,別寫錯了痢虹。


print(arg)

寫代碼實現(xiàn)如下功能:
若以前存儲了用戶名就加載它,否則提示用戶輸入用戶名并存儲它主儡。

import json
filename = 'name.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)   #不管是dump還是load都需要的是對象奖唯!也就是as后面那個東西,別寫錯了糜值。
except FileNotFoundError:
    arg = input("what is your name: ")
    with open(filename,'w') as f_obj:
        json.dump(arg,f_obj)   # 不管是dump還是load都需要的是對象丰捷!也就是as后面那個東西,別寫錯了寂汇。
        print("we will remember you when you come back " + arg)
else:
    print("welcome back " + username)
    

10.43的重構看書

第11章 測試代碼

使用Python模塊unittest 中的工具來測試代碼病往。
單元測試框架

測試函數(shù)

name_function.py

def funct(firstname,lastname):   #定義一個方法
    fullname = firstname + ' ' + lastname
    return fullname.title()

names.py

from name_function import funct    #從文件中導入方法
print("Enter 'q' at any time to quit.")
while True:
    firstname = input("Please give me a firstname: ")
    if firstname == 'q':
        break
    lastname = input("Please give me a lastname: ")
    if lastname == 'q':
        break
    fullname = funct(firstname,lastname)
    print(" \tNeatly formatted name: " + fullname + '.')

測試類

第15章 生成數(shù)據(jù)

matplotlib安裝

win + s   # 打開 cmd 命令行窗口

pip install wheel    # 安裝wheel
wheel   # 查看wheel是否安裝成功

pip wheel PyTZ
pip install pyparsing==1.5.6 --upgrade --user

pip install --user  matplotlib

使用matplotlib來畫圖
matplotlib官網(wǎng)

python -m pip install matplotlib
# 或者 pip install matplotlib
import matplotlib.pyplot as tmp    # 從matplotlib里面導入pyplot模塊
foo = [1,4,9,16,25]   # 創(chuàng)建列表
tmp.plot(foo)   # 將列表傳遞給函數(shù)plot
tmp.show()    # 顯示圖形
# 在cmd里面直接輸入jupyter notebook,即可使用jupyter notebook骄瓣。將上述代碼復制進它也能畫圖停巷。

圖片修改

plot.py

iimport matplotlib.pyplot as tmp   #導入模塊并指定別名

arg = [1,2,3,4,5,6,7,8,9,10]     # 同 arg =list(range(1,11))
foo = [1,4,9,16,25,36,49,64,81,100]    # 同 foo = [x**2 for x in arg] 從而實現(xiàn)自動計算


# tmp.plot(arg,foo,linewidth=6)   #arg和foo的位置順序?qū)藊y軸
tmp.scatter(arg,foo,s=200, edgecolor='none',c='red', cmap=tmp.cm.Blues)   
#.scatter()就是點圖; s為點尺寸榕栏; edgecolor是點輪廓色畔勤,none-沒有輪廓; 
#c是點填充色,c也可改成color #RGB顏色模式: c=(0,0.2,0.4,0.6,1.0)扒磁,越接近1顏色越淺庆揪,越接近0越深。#顏色映射: c=foo妨托; 
#cmap 告訴pyplot使用哪個顏色映射缸榛。Blues可換成Reds或者Greens試試(別忘了后面的s)。要了解pyplot 中所有的顏色映射兰伤, 請訪問http://matplotlib.org/ 仔掸, 單擊Examples, 向下滾動到Color Examples医清,再單擊colormaps_reference起暮。

#添加title和x、y軸坐標
tmp.title("Title",fontsize=11)    
tmp.xlabel("xlabel",fontsize= 22)
tmp.ylabel("ylabel", fontsize = 33)

tmp.tick_params(axis='both',which='major', labelsize = 10) # 設置刻度標記的大小;which有3個刻度会烙,major(主刻度線)负懦、minor(副刻度線)、both
tmp.axis([0,15,1,108])    # 設置坐標軸取值范圍

tmp.show()   #可替換成  tmp.savefig('C:/Users/HASEE/Desktop/tmp.png', bbox_inches='tight')     # 使用 別名.savefig()存儲圖片柏腻,指定路徑纸厉;若不指定路徑,則會保存在plot.py相同目錄下五嫂;bbox_inches='tight'是剪掉圖片空白位置颗品,省略此參數(shù)則保留空白位置肯尺。

15.3 隨機漫步

首先理解 randint 和 choice

#下面兩個例子都是在1,2,3之間任意選擇一個數(shù)賦值給左邊

from random import randint
tmp = randint(1,3)   # randint(a,b)表示獲取1到3之間的任何數(shù),包括1和3
print(tmp)    

from random import choice
tmp = choice([1,2,3]) #choice(1,3)表示獲取1到3之間的任何數(shù)躯枢,包括1和3
print(tmp)

ramdom_walk.py

from random import choice
class RandomWalk():
    def __init__(self,num_points=5000):    # __init__接受形參的值则吟,并將它們存儲在根據(jù)該類創(chuàng)建的實例屬性中。
        self.n_p = num_points    # 以self為前綴的變量可以供類中所有方法使用锄蹂。 這一步目的是獲取存儲在形參num_points中的值氓仲,并將其存儲到變量num_points中,然后該變量被關聯(lián)到當前創(chuàng)建的實例得糜。
        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):  #定義新方法敬扛,只有形參self,則后面創(chuàng)建的實例都能訪問該方法
        while len(self.x_values) < self.n_p:
            x_direction = choice([1,-1])    # 從[]里面隨機取一個值賦給左邊
            x_distance = choice([0,1,2,3,4])     
            x_step = x_direction * x_distance

            y_direction = choice([1,-1])
            y_distance = choice([0,1,2,3,4])
            y_step = y_direction * y_distance

            if x_step == 0 and y_step == 0:
                continue

            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step

            self.x_values.append(next_x)
            self.y_values.append(next_y)

rw_visual.py朝抖,運行該代碼可見隨機漫步圖

import matplotlib.pyplot as plt
from ramdom_walk import RandomWalk
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()

rw_visual.py代碼改成如下啥箭,則關閉查看器之后輸入y可模擬多次隨機漫步,并且對圖片進行了修飾

import matplotlib.pyplot as plt
from ramdom_walk import RandomWalk

while True:
    rw = RandomWalk()    #在()里面加入50000則可以將點數(shù)變成50000
    rw.fill_walk()

    #調(diào)整圖片寬治宣、高急侥、分辨率、背景色(若略則有默認尺寸)
    plt.figure(figsize=(10,10),dpi=128,facecolor='gray',edgecolor='red')   #.figure()可實現(xiàn)圖片調(diào)整炼七。dpi是分辨率;facecolor是背景色;edgecolor是畫板邊框顏色布持;

    #給點著色(若略則有默認色)
    n_p = list(range(rw.n_p))   
    plt.scatter(rw.x_values,rw.y_values,c=n_p,cmap = plt.cm.Reds,edgecolor = 'none', s=15)

    #重繪起/終點(若略則起/終點大小顏色與其它點無異)
    plt.scatter(0,0,c='green',edgecolor = 'none', s=100)  #重新繪制起點豌拙,使之明顯
    plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolor = 'none', s=200)  #重新繪制終點,使之明顯


    #隱藏坐標軸(若略則有坐標軸)
    plt.axes().get_xaxis().set_visible(False)   #改False為True有坐標軸
    plt.axes().get_yaxis().set_visible(False)

    plt.show()

    #多次隨機漫步
    keep_running = input("Make another walk? (y/n):")
    if keep_running == 'n':
        break

15.4 使用Pygal模擬擲骰子

訪問http://www.pygal.org/ 题暖, 單擊Documentation按傅, 再單擊Chart types。 可看到各種圖表且每個示例都有源代碼胧卤。

安裝pygal

pip install pygal

die.py

from random import randint
class Die():
    def __init__(self, num_sides=6):
        self.num_sides = num_sides
    def roll(self):
        return randint(1, self.num_sides)

die_visual.py

from die import Die

# 創(chuàng)建實例
die_1 = Die()   # 創(chuàng)建一個6面的骰子唯绍,因為默認為6
die_2 = Die(10)  # 創(chuàng)建一個10面的骰子
#上面兩個可修改為 die_1,die_2 = [],[]  這也是創(chuàng)建兩個空列表的方法

# 擲骰子
results = []    # 創(chuàng)建空列表
for roll_num in range(50000):   #使用for循環(huán)來擲骰子100次
    result = die_1.roll() + die_2.roll()   #使用for循環(huán)來擲骰子100次
    results.append(result)    #將result追加到列表results中

print(results)

# 分析結果
frequencies = []

for value in range(2,die_1.num_sides + die_2.num_sides +1):
    frequency = results.count(value)   #列表.count(value) 表示計算列表中value有幾個
    frequencies.append(frequency)   #將frequency追加到列表frequencies中
print(frequencies)

# 對結果進行可視化
import pygal
hist = pygal.Bar()  # 創(chuàng)建實例并存儲在hist中
hist.title = "Results of rolling a D6 and D10 50000 times."
hist.x_labels = [ '2', '3', '4', '5', '6','7','8','9','10','11','12','13','14','15','16']   # .x_labels是添加橫刻度值
hist.x_title = "Result"   # .x_title是添加橫標題
hist.y_title = "Frequency of Result"   # .x_title是添加橫標題
hist.add('D6 + D10', frequencies)  # 將frequencies中一系列的值添加到圖表中,這些值的標簽是D6枝誊。
hist.render_to_file('C:/Users/HASEE/Desktop/die_visual.svg')   # 將圖保存并命名 die_visual.svg,指定路徑况芒,若不指定路徑則圖和該代碼所在文件位于同一文件夾下。
import csv    #csv包含在python標椎庫中
from datetime import datetime #模塊中導入類

filename = 'C:/Users/HASEE/Desktop/sitka_weather_07-2014.csv'   # csv文件以逗號分割;將sitka_weather_07-2014.csv換成sitka_weather_2014.csv可繪制全年
with open(filename) as f:    #打開文件
    reader = csv.reader(f)    #讀取文件
    header_row = next(reader)   #返回第一行
    #print(header_row)

#for tmp,foo in enumerate(header_row):   #enumerate可獲取列表中每個元素的索引及其值
#    print(tmp,foo)

#提取并讀取數(shù)據(jù)
    arg,highs,dates = [],[],[]  #創(chuàng)建兩個空列表叶撒,一個用來存貯字符串绝骚,另一個存儲數(shù)字。
    #arg = []  #再創(chuàng)建空列表等會兒存貯數(shù)字
    for row in reader:   #遍歷行祠够; #reader就是對象(object)压汪;row是對象每行;row[1]表示對象每行第二列古瓤,若為-1則為最后一列止剖;
        highs.append(row[1]) #將每行第二個值追加到列表highs里面腺阳。
        foo = int(row[1])  #int()將字符串轉成數(shù)字
        arg.append(foo)    #將數(shù)字追加到列表arg里面

#在圖表中添加日期
        current_date = datetime.strptime(row[0], "%Y-%m-%d")  # 第一個實參是row[0],是對象每行第一列(日期)穿香;第二個實參告訴python如何設置日期格式亭引。
        dates.append(current_date)

    print(highs)
    print(arg)

#根據(jù)數(shù)據(jù)繪制圖形
from matplotlib import pyplot as plt
fig = plt.figure(dpi = 128, figsize = (10,6))
plt.plot(arg,c= 'red')
plt.plot(dates,arg,c='red')

#設置圖形格式
fig.autofmt_xdate()   #繪制斜日期標簽,避免重疊
plt.title("aaa",fontsize=36,c='pink')
plt.xlabel("x label",fontsize = 36,c='pink')
plt.ylabel("y label",fontsize = 36,c='pink')
plt.tick_params(axis='both',which='both',labelsize=16)# 設置刻度標記的大小;which有3個刻度扔水,major(主刻度線)痛侍、minor(副刻度線)、both
plt.axis([0,40,30,100])    # 設置坐標軸取值范圍

plt.show()

16.1.7

import csv    #csv包含在python標椎庫中
from datetime import datetime #模塊中導入類

filename = 'C:/Users/HASEE/Desktop/sitka_weather_2014.csv'   # csv文件以逗號分割;將sitka_weather_07-2014.csv換成sitka_weather_2014.csv可繪制全年
with open(filename) as f:    #打開文件
    reader = csv.reader(f)    #讀取文件
    header_row = next(reader)   #返回第一行

#提取并讀取數(shù)據(jù)
    highs,dates = [],[]  #創(chuàng)建兩個空列表魔市,一個用來存貯字符串主届,另一個存儲數(shù)字。
    for row in reader:   #遍歷行待德; #reader就是對象(object)君丁;row是對象每行;row[1]表示對象每行第二列将宪,若為-1則為最后一列绘闷;
        current_date = datetime.strptime(row[0], "%Y-%m-%d")  # 第一個實參是row[0],是對象每行第一列(日期)较坛;第二個實參告訴python如何設置日期格式印蔗。
        dates.append(current_date)
        high = int(row[1])  #int()將字符串轉成數(shù)字
        highs.append(high)    #將數(shù)字追加到列表arg里面

#根據(jù)數(shù)據(jù)繪制圖形
from matplotlib import pyplot as plt
fig = plt.figure(dpi = 128, figsize = (10,6))
plt.plot(dates,highs,c='red')

#設置圖形格式
fig.autofmt_xdate()   #繪制斜日期標簽,避免重疊
plt.title("aaa",fontsize=36,c='pink')
plt.xlabel("x label",fontsize = 36,c='pink')
plt.ylabel("y label",fontsize = 36,c='pink')
plt.tick_params(axis='both',which='both',labelsize=16)# 設置刻度標記的大小;which有3個刻度丑勤,major(主刻度線)华嘹、minor(副刻度線)、both
plt.show()

16.1.9

import csv    #csv包含在python標椎庫中
from datetime import datetime #模塊中導入類

filename = 'C:/Users/HASEE/Desktop/sitka_weather_2014.csv'   # csv文件以逗號分割;將sitka_weather_07-2014.csv換成sitka_weather_2014.csv可繪制全年
with open(filename) as f:    #打開文件
    reader = csv.reader(f)    #讀取文件
    header_row = next(reader)   #返回第一行

#提取并讀取數(shù)據(jù)
    highs,lows,dates = [],[],[]  #創(chuàng)建兩個空列表法竞,一個用來存貯字符串耙厚,另一個存儲數(shù)字。
    for row in reader:   #遍歷行岔霸; #reader就是對象(object)薛躬;row是對象每行;row[1]表示對象每行第二列呆细,若為-1則為最后一列型宝;很多數(shù)據(jù)集都可能缺失數(shù)據(jù)、 數(shù)據(jù)格式不正確或數(shù)據(jù)本身不正確絮爷。 此時可使用 try-exceptelse 代碼塊來處理數(shù)據(jù)缺失的問題诡曙。 有時使用continue 跳過一些數(shù)據(jù), 或者remove() 或del 將已提取的數(shù)據(jù)刪除略水。
        current_date = datetime.strptime(row[0], "%Y-%m-%d")  # 第一個實參是row[0]价卤,是對象每行第一列(日期)售貌;第二個實參告訴python如何設置日期格式宅倒。
        dates.append(current_date)
        high = int(row[1])  #int()將字符串轉成數(shù)字
        highs.append(high)    #將數(shù)字追加到列表arg里面
        low = int(row[3])  #每行的第四列是最低氣溫
        lows.append(low)


#根據(jù)數(shù)據(jù)繪制圖形
from matplotlib import pyplot as plt
fig = plt.figure(dpi = 128, figsize = (10,6))
plt.plot(dates,highs,c='red',alpha=0.5)  # 根據(jù)日期對最高氣溫畫圖扼睬;alpha表示透明度哄孤,1完全不透明(默認),0完全透明胸私。
plt.plot(dates,lows,c='blue',alpha=0.5)  # 根據(jù)日期對最低氣溫畫圖
plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1)  #填充兩條線之間的區(qū)域厌处,dates對應兩個y值,將之間的區(qū)域填充岁疼。


#設置圖形格式
fig.autofmt_xdate()   #繪制斜日期標簽阔涉,避免重疊
plt.title("aaa",fontsize=36,c='pink')
plt.xlabel("x label",fontsize = 36,c='pink')
plt.ylabel("y label",fontsize = 36,c='pink')
plt.tick_params(axis='both',which='both',labelsize=16)# 設置刻度標記的大小;which有3個刻度,major(主刻度線)捷绒、minor(副刻度線)瑰排、both
plt.show()

16.2

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市暖侨,隨后出現(xiàn)的幾起案子椭住,更是在濱河造成了極大的恐慌,老刑警劉巖字逗,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件京郑,死亡現(xiàn)場離奇詭異,居然都是意外死亡葫掉,警方通過查閱死者的電腦和手機些举,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來俭厚,“玉大人户魏,你說我怎么就攤上這事√赘梗” “怎么了绪抛?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵资铡,是天一觀的道長电禀。 經(jīng)常有香客問我,道長笤休,這世上最難降的妖魔是什么尖飞? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮店雅,結果婚禮上政基,老公的妹妹穿的比我還像新娘。我一直安慰自己闹啦,他們只是感情好沮明,可當我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著窍奋,像睡著了一般荐健。 火紅的嫁衣襯著肌膚如雪酱畅。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天江场,我揣著相機與錄音纺酸,去河邊找鬼。 笑死址否,一個胖子當著我的面吹牛餐蔬,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播佑附,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼樊诺,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了帮匾?” 一聲冷哼從身側響起啄骇,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎瘟斜,沒想到半個月后缸夹,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡螺句,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年虽惭,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蛇尚。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡芽唇,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出取劫,到底是詐尸還是另有隱情匆笤,我是刑警寧澤,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布谱邪,位于F島的核電站炮捧,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏惦银。R本人自食惡果不足惜咆课,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望扯俱。 院中可真熱鬧书蚪,春花似錦、人聲如沸迅栅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽读存。三九已至为流,卻和暖如春窜醉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背艺谆。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工榨惰, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人静汤。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓琅催,卻偏偏與公主長得像,于是被迫代替她去往敵國和親虫给。 傳聞我的和親對象是個殘疾皇子藤抡,可洞房花燭夜當晚...
    茶點故事閱讀 44,955評論 2 355