第2部分:Python入門(mén)
Python入門(mén)總共分為:
- 編程入門(mén) - Turtle
- 為何要學(xué)習(xí) Python 編程
- 數(shù)據(jù)類(lèi)型和運(yùn)算符
- 數(shù)據(jù)結(jié)構(gòu)
- 控制流
- 函數(shù)
- 腳本編寫(xiě)
- NumPy
- Pandas
一、編程入門(mén) - Turtle
1、變量
變量就是將代碼中的名稱(chēng)與計(jì)算機(jī)中的數(shù)據(jù)關(guān)聯(lián)
amy = turtle.Turtle()
??這一個(gè)行為叫做賦值,‘=’稱(chēng)為賦值運(yùn)算符
案例:
import turtle
amy = turtle.Turtle() #命名turtle為‘a(chǎn)my’,amy就是變量名稱(chēng)。注意,Python 區(qū)分大小寫(xiě)。例如,在 turtle.Turtle() 中,Turtle() 中的 T 大寫(xiě)了。因此 turtle 與 Turtle 含義不一樣。我們說(shuō) Python 是一個(gè)區(qū)分大小寫(xiě)的編程語(yǔ)言。
amy.color("red")
amy.forward(100)
amy.right(135)
amy.forward(140)
amy.right(135)
amy.forward(100)
2、字符串
上邊案例中的單詞 "yellow" 和 "green" 稱(chēng)為字符串。字符串需要用“”擴(kuò)起來(lái)
3、列表
在 Python 中,列表放入方括號(hào)里,并且用逗號(hào)分隔各項(xiàng)。
[1, 2, 3, 4, 5] 和 [7, 2, 1, 0, 9] 屬于列表,也可以將字符串放入列表里:["hello", "yellow", "stuff", "things"]

4、畫(huà)圖常用到的命令
import turtle
amy = turtle.Turtle()
pretty_color="yellow"
amy.color(pretty_color) #線的顏色是黃色,我們還可以定義很多別的變量,都要放在指令運(yùn)行前。
amy.width(10) #寬度是10
amy.speed(8) #畫(huà)圖速度是8,最快畫(huà)完是speed(0)
amy.penup() #停止繪制
amy.pendown()開(kāi)始繪制
- 注釋代碼:#
需要對(duì)多行代碼進(jìn)行注釋?zhuān)ㄈ∠⑨專(zhuān)?,只需選中要注釋掉(取消注釋?zhuān)┑拇a行,然后按下快捷鍵【?/】即可。
5、循環(huán)
import turtle
amy = turtle.Turtle()
amy.color("yellow")
for side in [1, 2, 3, 4, 5]: #1、中括號(hào)后必須加冒號(hào);2、循環(huán)次數(shù)取決于中括號(hào)中有幾項(xiàng)
amy.forward(100) #循環(huán)內(nèi)容要向右移動(dòng)四個(gè)空格
amy.right(72) #循環(huán)內(nèi)容要向右移動(dòng)四個(gè)空格
6、列表和循環(huán)
import turtle
lengths = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100,110,120,130,140] #做了賦值以后,lengths在后邊就會(huì)被用到了
amy = turtle.Turtle()
amy.color("yellow")
amy.width(2)
for length in lengths: #這句話就相當(dāng)于for length in [10, 20, 30, 40, 50, 60, 70, 80, 90, 100,110,120,130,140]:
amy.forward(length)
amy.right(90)

7、嵌套循環(huán)
import turtle
amy = turtle.Turtle()
# Make the width thicker so that the line will be easier to see
# 使線條寬度加粗,以便更容易看到線條
amy.width(5)
# Move back without drawing anything
# 向后移動(dòng)且不畫(huà)任何東西
amy.penup()
amy.forward(-140)
amy.pendown()
# Draw three shapes of different colors, with space in between
#繪制三種不同顏色的形狀,形狀間用空格間隔
for prettycolor in ["red", "orange", "yellow"]:
amy.color(prettycolor)
for side in [1, 2, 3, 4]:
amy.forward(50)
amy.right(90)
amy.penup()
amy.forward(100)
amy.pendown()
8、錯(cuò)誤bug
編程中會(huì)出現(xiàn)三大類(lèi)型的錯(cuò)誤:語(yǔ)法錯(cuò)誤、用法錯(cuò)誤和邏輯錯(cuò)誤。
9、other
其他 turtle 的使用方法:
- amy.hideturtle() 將使 turtle 本身消失。
- amy.showturtle() 將使其再次出現(xiàn)。
和下邊的很相像?? - amy.penup() 將使其“抬筆”并且在移動(dòng)時(shí)不繪制線條。
- amy.pendown() 將使其再次移動(dòng)時(shí)開(kāi)始繪制圖形。
二、為何要學(xué)習(xí) Python 編程
這一部分沒(méi)什么有用的內(nèi)容,小姐姐主要就是想說(shuō),Python很有用。

幾個(gè)注意事項(xiàng):
Python 區(qū)分大小寫(xiě);
空格很重要;
通過(guò)報(bào)錯(cuò) Error Message 了解錯(cuò)誤信息;
三、數(shù)據(jù)類(lèi)型和運(yùn)算符
Python的構(gòu)建基石:數(shù)據(jù)類(lèi)型和運(yùn)算符
??算數(shù)運(yùn)算符
+ 加(addition)
- 減(subtraction)
* 乘(multiplication)
/ 除(division)
% 取模(相除后的余數(shù))(mo du lo)
** 取冪(exponentiation)
//相除后向下取整到最接近的整數(shù)(integer division)
#注意:取模運(yùn)算和取余運(yùn)算是一個(gè)非常容易混淆的概念
算數(shù)運(yùn)算符更多信息:https://wiki.python.org/moin/BitwiseOperators
??變量和賦值運(yùn)算符
變量
1、變量名稱(chēng)中,只能使用常規(guī)字母、數(shù)字和下劃線。不能包含空格,并且需要以字母或下劃線開(kāi)頭。
2、不能使用保留字和內(nèi)置標(biāo)識(shí)符(下圖是保留字的簡(jiǎn)單表格)保留字
3、變量名稱(chēng)的命名方式是全部使用小寫(xiě)字母,并用下劃線區(qū)分單詞

賦值運(yùn)算符
賦值運(yùn)算符的使用方式
X=2 ?? X=2
X+=2 ?? X=X+2
X-=2 ?? X=X-2

練習(xí):賦值和修改變量:
# The current volume of a water reservoir (in cubic metres)
reservoir_volume = 4.445e8
# The amount of rainfall from a storm (in cubic metres)
rainfall = 5e6
# decrease the rainfall variable by 10% to account for runoff
rainfall *= (1-0.1)
# add the rainfall variable to the reservoir_volume variable
reservoir_volume=rainfall+reservoir_volume
# increase reservoir_volume by 5% to account for stormwater that flows
# into the reservoir in the days following the storm
reservoir_volume *= (1+0.05)
# decrease reservoir_volume by 5% to account for evaporation
reservoir_volume *= (1-0.05)
# subtract 2.5e5 cubic metres from reservoir_volume to account for water
# that's piped to arid regions.
reservoir_volume -= 2.5e5
# print the new value of the reservoir_volume variable
print(reservoir_volume)
代碼如上,做這道題我出現(xiàn)了兩個(gè)小錯(cuò)誤。1??:括號(hào)沒(méi)有用英文的;2??忘記不能用%了,比如5%,在Python里就用0.05。
還有一個(gè)沒(méi)搞太明白的就是這一步,感覺(jué)很奇怪。。。。
注釋?zhuān)篴dd the rainfall variable to the reservoir_volume variable
reservoir_volume=rainfall+reservoir_volume
答案:447627500.0
更改變量
print(int(mv_density))
int的意思是整數(shù)
??整數(shù)和浮點(diǎn)數(shù)
int - 表示整數(shù)值(integer)
float - 表示小數(shù)或浮點(diǎn)數(shù)值

>>> print(.1 + .1 + .1 == .3)
False
0.1+0.1+0.1會(huì)大于0.3是因?yàn)檫M(jìn)制不同https://docs.python.org/3/tutorial/floatingpoint.html
- 關(guān)于代碼格式的問(wèn)題:PEP 8 -- Style Guide for Python Code
- 代碼報(bào)錯(cuò)問(wèn)題: Errors and Exceptions
](https://docs.python.org/3/tutorial/errors.html)
??布爾運(yùn)算符、比較運(yùn)算符、邏輯運(yùn)算符
1、布爾運(yùn)算:
布爾運(yùn)算的發(fā)明者:George Boole
bool是boolean的縮寫(xiě),是專(zhuān)門(mén)處理ture/false的變量
布爾數(shù)據(jù)類(lèi)型存儲(chǔ)的是值 True 或 False,通常分別表示為 1 或 0。
通常有 6 個(gè)比較運(yùn)算符會(huì)獲得布爾值:也就是下邊的比較運(yùn)算
2、比較運(yùn)算:
< 小于
<= 小于等于
> 大于
>= 大于等于
== 等于
!= 不等于
3、邏輯運(yùn)算符
and:比較兩邊是否都是true
or:是否至少一側(cè)為true
not:顛倒布爾類(lèi)型
??字符串
字符串的變量類(lèi)型為“str”
使用雙引號(hào)或者單引號(hào)定義字符串
>>> this_string = 'Simon\'s skateboard is in the garage.'
>>> print(this_string)
字符串也可以進(jìn)行?和??,不可以?和?
first_word='hello'
second_word='baby'
print(first_word+second_word)
結(jié)果會(huì)是:hellobaby,中間沒(méi)有空格,如果我們需要有空格,則需要
print(first_word+“ ”+second_word)
內(nèi)置函數(shù)len:
len 僅適用于“序列(例如字符串、字節(jié)、元組、列表或范圍)或集合(例如字典、集合或凍結(jié)集合)”。
>>> first_word = 'Hello'
>>> second_word = 'There'
>>> print(first_word + second_word)
HelloThere
>>> print(first_word + ' ' + second_word)
Hello There
>>> print(first_word * 5)
HelloHelloHelloHelloHello
>>> print(len(first_word))
5
??數(shù)據(jù)類(lèi)型:
四種數(shù)據(jù)類(lèi)型:
整型_int【5】
浮點(diǎn)型_float【5.4】
布爾型_bool【true】
字符串_str【'hello'】
可以用“type”來(lái)查看數(shù)據(jù)類(lèi)型
print(type(55))
<class 'int'>
??字符串方法
方法就像某些你已經(jīng)見(jiàn)過(guò)的函數(shù):
len("this")
type(12)
print("Hello world")
上述三項(xiàng)都是函數(shù)。
方法:
像:title(題目首字母大寫(xiě))、islower(檢查是否都是小寫(xiě))、
print("jizhi julebu".title())
Jizhi Julebu
#title的方法使用??
name="hannah"
print(name.islower())
true

count 和 find 方法都接受另一個(gè)參數(shù)。但是,islower 方法不接受參數(shù)
>>>my_string="sebastion thrun"
>>> my_string.islower()
True
>>> my_string.count('a')
2
>>> my_string.find('a')
3
所有記不住的方法,來(lái)這里調(diào)用:https://docs.python.org/3/library/stdtypes.html#string-methods
find('hannah')
hannah第一次出現(xiàn)的位置
rfind('hannah')
hannah最后一次出現(xiàn)的位置
四、數(shù)據(jù)結(jié)構(gòu)
數(shù)據(jù)結(jié)構(gòu)類(lèi)型:
- 列表
- 元組
- 集
- 字典
- 復(fù)合數(shù)據(jù)結(jié)構(gòu)
??1、列表 [ ]
list是 Python 中最常見(jiàn)和最基本的數(shù)據(jù)結(jié)構(gòu)之一。
列表可排序,你可以使用 .append 向列表中添加項(xiàng)目,列表項(xiàng)的索引始終以 0 開(kāi)始。'
lst_of_random_things = [1, 3.4, 'a string', True] #整數(shù)、浮點(diǎn)數(shù)、字符串、布爾
print(lst_of_random_things[4])
True
print(lst_of_random_things[-3])
a string
??列表切片
lst_of_random_things = [1, 3.4, 'a string', True] #整數(shù)、浮點(diǎn)數(shù)、字符串、布爾
print(lst_of_random_things[1:2])
[3.4]
print(lst_of_random_things[:4])
[3.4, 'a string', True]
起始索引包含在內(nèi),終止索引排除在外。
字符串和列表的區(qū)別是:
字符串有一系列字母組成;
列表可以由任何元素組成;
mutability=可變性
??在列表中的列表方法:
len()表示元素?cái)?shù)量
max()表示最大元素
min()表示最小元素
sorted()表示從小到大排序,加reverse則相反
Join,是一個(gè)字符串方法,它將字符串列表作為參數(shù),并返回由分隔符字符串連接的列表元素組成的字符串。
new_str = "\n".join(["fore", "aft", "starboard", "port"])
print(new_str)
??
fore
aft
starboard
port
append的方法非常有用,它將一個(gè)元素添加到列表的末尾。
letters = ['a', 'b', 'c', 'd']
letters.append('z')
print(letters)
??
['a', 'b', 'c', 'd', 'z']
數(shù)據(jù)結(jié)構(gòu)&數(shù)據(jù)類(lèi)型??
數(shù)據(jù)類(lèi)型只是一種對(duì)數(shù)據(jù)進(jìn)行分類(lèi)的類(lèi)型。 這可以包括原始(基本)數(shù)據(jù)類(lèi)型,如整數(shù),布爾值和字符串,以及數(shù)據(jù)結(jié)構(gòu),如列表。
數(shù)據(jù)結(jié)構(gòu)是以不同方式組織和分組數(shù)據(jù)類(lèi)型的容器。 例如,列表可以包含的一些元素是整數(shù),字符串,甚至是其他列表!
關(guān)于切片索引:記住,切片的較低索引是包括進(jìn)去的,而較高索引是不包括在內(nèi)的。
??2、元組(tuples)
元組不能像列表一樣可以修改,有序但不可以排序;
元組的 小括號(hào)是可選的,也可以不要
??3、集合(set)
集合是一個(gè)包含唯一元素的可變無(wú)序集合數(shù)據(jù)類(lèi)型。集合的一個(gè)用途是快速刪除列表中的重復(fù)項(xiàng)。
【收集唯一元素,檢查重復(fù)元素】
- 集合是無(wú)序的,因此項(xiàng)目的出現(xiàn)順序可能不一致,你可以使用 .add 向集合中添加項(xiàng)目。和字典及列表一樣,集合是可變的。
numbers = [1, 2, 6, 3, 1, 1, 6]
unique_nums = set(numbers)
print(unique_nums)
??
{1, 2, 3, 6}
你可以對(duì)集合執(zhí)行的其他操作包括可以對(duì)數(shù)學(xué)集合執(zhí)行的操作。可以對(duì)集合輕松地執(zhí)行 union、intersection 和 difference 等方法,并且與其他容器相比,速度快了很多。
??4、字典和恒等運(yùn)算符
字典是可變數(shù)據(jù)類(lèi)型,其中存儲(chǔ)的是唯一鍵到值的映射。
elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
print(elements["helium"]) # print the value mapped to "helium"
elements["lithium"] = 3 # insert "lithium" with a value of 3 into the dictionary
print("carbon" in elements)
print(elements.get("dilithium"))
??
True
None
集合可以用花括號(hào)來(lái)定義,但并不是唯一的——字典也可以用花括號(hào)來(lái)定義。但是,兩者不同之處在于集合是由逗號(hào)分隔的元素序列,而字典是一系列用冒號(hào)標(biāo)記的鍵值對(duì),用逗號(hào)分隔.
??5、復(fù)合數(shù)據(jù)結(jié)構(gòu)
elements = {"hydrogen": {"number": 1,
"weight": 1.00794,
"symbol": "H"},
"helium": {"number": 2,
"weight": 4.002602,
"symbol": "He"}}
總結(jié)
總結(jié)直接截圖了,其實(shí)再次重復(fù)一遍。
感覺(jué),學(xué)數(shù)據(jù)結(jié)構(gòu)最大的感受就是,多練習(xí)?。?!這個(gè)最重要了,當(dāng)時(shí)覺(jué)得看懂了概念,做的時(shí)候還是一臉懵逼。。。。練習(xí)才是最重要的 !??!

五、控制流
學(xué)習(xí)這部分,一本入門(mén)書(shū)對(duì)我的作用還是蠻大的,推薦~《Python編程從入門(mén)到實(shí)踐》,下載鏈接如下(網(wǎng)上很多,)
https://www.jb51.net/books/510188.html
- 條件語(yǔ)句
- 布爾表達(dá)式
- For 和 While 循環(huán)
- Break 和 Continue
- Zip 和 Enumerate
- 列表推導(dǎo)式
??1、條件語(yǔ)句
if 語(yǔ)句是是一種條件語(yǔ)句,根據(jù)條件為 true 還是 false 運(yùn)行或執(zhí)行相關(guān)代碼。
注意:第一行最后加冒號(hào)(colon)下邊開(kāi)始鎖進(jìn),循環(huán)語(yǔ)句
if phone_balance < 5: #條件用布爾表達(dá)式指定,結(jié)果為 True 或 False。
phone_balance += 10
bank_balance -= 10
- If、Elif、Else
elif=if else
if開(kāi)頭,elif中間,else最后
if season == 'spring': #用==,意思是等于,而不是=,=是賦值的意思
print('plant the garden!')
elif season == 'summer':
print('water the garden!')
elif season == 'fall':
print('harvest the garden!')
elif season == 'winter':
print('stay indoors!')
else:
print('unrecognized season')
- 縮進(jìn)
在 Python 中,縮進(jìn)通常是四個(gè)空格一組
**注意??:if 設(shè)置完最后,一定別忘記加冒號(hào):,等于號(hào)用==。=是賦值
??2、布爾表達(dá)式
- 請(qǐng)勿使用 True 或 False 作為條件
- 在使用邏輯運(yùn)算符編寫(xiě)表達(dá)式時(shí),要謹(jǐn)慎(邏輯運(yùn)算符 and、or 和 not 具有特定的含義)
# Bad example
if weather == "snow" or "rain":
print("Wear boots!")
- 請(qǐng)勿使用 == True 或 == False 比較布爾變量
??3、For和While循環(huán)
- Python 有兩種類(lèi)型的循環(huán):for 循環(huán)和 while 循環(huán)。for 循環(huán)用來(lái)遍歷可迭代對(duì)象。
# iterable of cities
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
# for loop that iterates over the cities list
for city in cities:
print(city.title())
# Creating a new list
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
capitalized_cities = []
for city in cities:
capitalized_cities.append(city.title())
range() 是一個(gè)內(nèi)置函數(shù),用于創(chuàng)建不可變的數(shù)字序列。它有三個(gè)參數(shù),必須都為整數(shù)。9i
range(start=0, stop, step=1)
Start是該序列的第一個(gè)數(shù)字,stop比該序列的最后一個(gè)數(shù)字大 1,step是該序列中每個(gè)數(shù)字之間的差。
將 range 封裝在列表中。
創(chuàng)建和修改:
# Creating a new list
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
capitalized_cities = []
for city in cities:
capitalized_cities.append(city.title())
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for index in range(len(cities)):
cities[index] = cities[index].title()
for i in range(3):
print("Hello!")
標(biāo)記計(jì)數(shù)器:
可以使用字符串索引判斷每個(gè)令牌是否以尖括號(hào)開(kāi)始和結(jié)束。
tokens = ['<greeting>', 'Hello World!', '</greeting>']
count = 0
for i in tokens:
if i[0]=='<' and i[-1]=='>':
count+=1 #x+=1??x=x+1
# write your for loop here
print(count)
創(chuàng)建html(添加)
寫(xiě)一個(gè) for 循環(huán),用于遍歷字符串列表并創(chuàng)建單個(gè)字符串 html_str,它是一個(gè) HTML 列表。例如,如果列表是 items = ['first string', 'second string],輸出 html_str 應(yīng)該會(huì)輸出:
<ul>
<li>first string</li>
<li>second string</li>
</ul>
items = ['first string', 'second string']
html_str = "<ul>\n"
for item in items:
html_str += "<li>{}</li>\n".format(item)
html_str += "</ul>"
print(html_str)
創(chuàng)建字典
方法1:使用for循環(huán)創(chuàng)建一組計(jì)數(shù)器
book_title = ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gasby','hamlet','adventures','of','huckleberry','fin']
word_counter = {}
for word in book_title:
if word not in word_counter:
word_counter[word] = 1
else:
word_counter[word] += 1
方法 2: 使用 get 方法
book_title = ['great', 'expectations','the', 'adventures', 'of', 'sherlock','holmes','the','great','gasby','hamlet','adventures','of','huckleberry','fin']
word_counter = {}
for word in book_title:
word_counter[word] = word_counter.get(word, 0) + 1
for 循環(huán)字典:
for key, value in cast.items():
print("Actor: {} Role: {}".format(key, value))
整數(shù)的階乘 (**) 是該數(shù)字乘以自身與1之間的每個(gè)整數(shù)的乘積。例如,6的階乘(寫(xiě)為“ 6!”)等于6 x 5 x 4 x 3 x 2 x 1 = 720,即:6! = 720。
- 求1-100的和
i=0
result=0
while i<= 100:
result+=i
i+=1
print("1-100的和是%d"%result)
??4、Break和Continue
break&continue:
- break 使循環(huán)終止
- continue 跳過(guò)循環(huán)的一次迭代
保留前140個(gè)字符:
headlines = ["Local Bear Eaten by Man",
"Legislature Announces New Laws",
"Peasant Discovers Violence Inherent in System",
"Cat Rescues Fireman Stuck in Tree",
"Brave Knight Runs Away",
"Papperbok Review: Totally Triffic"]
news_ticker = ""
for headline in headlines:
news_ticker += headline + " "
if len(news_ticker) >= 140:
news_ticker = news_ticker[:140]
break
print(news_ticker)
??5、Zip 和 Enumerate
- zip 返回一個(gè)將多個(gè)可迭代對(duì)象組合成一個(gè)元組序列的迭代器。每個(gè)元組都包含所有可迭代對(duì)象中該位置的元素。
-
enumerate 是一個(gè)會(huì)返回元組迭代器的內(nèi)置函數(shù),這些元組包含列表的索引和值。當(dāng)你需要在循環(huán)中獲取可迭代對(duì)象的每個(gè)元素及其索引時(shí),將經(jīng)常用到該函數(shù)。
eg:
??6、列表推導(dǎo)式
列表推導(dǎo)式可以簡(jiǎn)寫(xiě)代碼:
eg:
capitalized_cities = []
for city in cities:
capitalized_cities.append(city.title())
相當(dāng)于??
capitalized_cities = [city.title() for city in cities]
作業(yè):
nominated = {1931: ['Norman Taurog', 'Wesley Ruggles', 'Clarence Brown', 'Lewis Milestone', 'Josef Von Sternberg'], 1932: ['Frank Borzage', 'King Vidor', 'Josef Von Sternberg'], 1933: ['Frank Lloyd', 'Frank Capra', 'George Cukor'], 1934: ['Frank Capra', 'Victor Schertzinger', 'W. S. Van Dyke'], 1935: ['John Ford', 'Michael Curtiz', 'Henry Hathaway', 'Frank Lloyd'], 1936: ['Frank Capra', 'William Wyler', 'Robert Z. Leonard', 'Gregory La Cava', 'W. S. Van Dyke'], 1937: ['Leo McCarey', 'Sidney Franklin', 'William Dieterle', 'Gregory La Cava', 'William Wellman'], 1938: ['Frank Capra', 'Michael Curtiz', 'Norman Taurog', 'King Vidor', 'Michael Curtiz'], 1939: ['Sam Wood', 'Frank Capra', 'John Ford', 'William Wyler', 'Victor Fleming'], 1940: ['John Ford', 'Sam Wood', 'William Wyler', 'George Cukor', 'Alfred Hitchcock'], 1941: ['John Ford', 'Orson Welles', 'Alexander Hall', 'William Wyler', 'Howard Hawks'], 1942: ['Sam Wood', 'Mervyn LeRoy', 'John Farrow', 'Michael Curtiz', 'William Wyler'], 1943: ['Michael Curtiz', 'Ernst Lubitsch', 'Clarence Brown', 'George Stevens', 'Henry King'], 1944: ['Leo McCarey', 'Billy Wilder', 'Otto Preminger', 'Alfred Hitchcock', 'Henry King'], 1945: ['Billy Wilder', 'Leo McCarey', 'Clarence Brown', 'Jean Renoir', 'Alfred Hitchcock'], 1946: ['David Lean', 'Frank Capra', 'Robert Siodmak', 'Clarence Brown', 'William Wyler'], 1947: ['Elia Kazan', 'Henry Koster', 'Edward Dmytryk', 'George Cukor', 'David Lean'], 1948: ['John Huston', 'Laurence Olivier', 'Jean Negulesco', 'Fred Zinnemann', 'Anatole Litvak'], 1949: ['Joseph L. Mankiewicz', 'Robert Rossen', 'William A. Wellman', 'Carol Reed', 'William Wyler'], 1950: ['Joseph L. Mankiewicz', 'John Huston', 'George Cukor', 'Billy Wilder', 'Carol Reed'], 1951: ['George Stevens', 'John Huston', 'Vincente Minnelli', 'William Wyler', 'Elia Kazan'], 1952: ['John Ford', 'Joseph L. Mankiewicz', 'Cecil B. DeMille', 'Fred Zinnemann', 'John Huston'], 1953: ['Fred Zinnemann', 'Charles Walters', 'William Wyler', 'George Stevens', 'Billy Wilder'], 1954: ['Elia Kazan', 'George Seaton', 'William Wellman', 'Alfred Hitchcock', 'Billy Wilder'], 1955: ['Delbert Mann', 'John Sturges', 'Elia Kazan', 'Joshua Logan', 'David Lean'], 1956: ['George Stevens', 'Michael Anderson', 'William Wyler', 'Walter Lang', 'King Vidor'], 1957: ['David Lean', 'Mark Robson', 'Joshua Logan', 'Sidney Lumet', 'Billy Wilder'], 1958: ['Richard Brooks', 'Stanley Kramer', 'Robert Wise', 'Mark Robson', 'Vincente Minnelli'], 1959: ['George Stevens', 'Fred Zinnemann', 'Jack Clayton', 'Billy Wilder', 'William Wyler'], 1960: ['Billy Wilder', 'Jules Dassin', 'Alfred Hitchcock', 'Jack Cardiff', 'Fred Zinnemann'], 1961: ['J. Lee Thompson', 'Robert Rossen', 'Stanley Kramer', 'Federico Fellini', 'Robert Wise', 'Jerome Robbins'], 1962: ['David Lean', 'Frank Perry', 'Pietro Germi', 'Arthur Penn', 'Robert Mulligan'], 1963: ['Elia Kazan', 'Otto Preminger', 'Federico Fellini', 'Martin Ritt', 'Tony Richardson'], 1964: ['George Cukor', 'Peter Glenville', 'Stanley Kubrick', 'Robert Stevenson', 'Michael Cacoyannis'], 1965: ['William Wyler', 'John Schlesinger', 'David Lean', 'Hiroshi Teshigahara', 'Robert Wise'], 1966: ['Fred Zinnemann', 'Michelangelo Antonioni', 'Claude Lelouch', 'Richard Brooks', 'Mike Nichols'], 1967: ['Arthur Penn', 'Stanley Kramer', 'Richard Brooks', 'Norman Jewison', 'Mike Nichols'], 1968: ['Carol Reed', 'Gillo Pontecorvo', 'Anthony Harvey', 'Franco Zeffirelli', 'Stanley Kubrick'], 1969: ['John Schlesinger', 'Arthur Penn', 'George Roy Hill', 'Sydney Pollack', 'Costa-Gavras'], 1970: ['Franklin J. Schaffner', 'Federico Fellini', 'Arthur Hiller', 'Robert Altman', 'Ken Russell'], 1971: ['Stanley Kubrick', 'Norman Jewison', 'Peter Bogdanovich', 'John Schlesinger', 'William Friedkin'], 1972: ['Bob Fosse', 'John Boorman', 'Jan Troell', 'Francis Ford Coppola', 'Joseph L. Mankiewicz'], 1973: ['George Roy Hill', 'George Lucas', 'Ingmar Bergman', 'William Friedkin', 'Bernardo Bertolucci'], 1974: ['Francis Ford Coppola', 'Roman Polanski', 'Francois Truffaut', 'Bob Fosse', 'John Cassavetes'], 1975: ['Federico Fellini', 'Stanley Kubrick', 'Sidney Lumet', 'Robert Altman', 'Milos Forman'], 1976: ['Alan J. Pakula', 'Ingmar Bergman', 'Sidney Lumet', 'Lina Wertmuller', 'John G. Avildsen'], 1977: ['Steven Spielberg', 'Fred Zinnemann', 'George Lucas', 'Herbert Ross', 'Woody Allen'], 1978: ['Hal Ashby', 'Warren Beatty', 'Buck Henry', 'Woody Allen', 'Alan Parker', 'Michael Cimino'], 1979: ['Bob Fosse', 'Francis Coppola', 'Peter Yates', 'Edouard Molinaro', 'Robert Benton'], 1980: ['David Lynch', 'Martin Scorsese', 'Richard Rush', 'Roman Polanski', 'Robert Redford'], 1981: ['Louis Malle', 'Hugh Hudson', 'Mark Rydell', 'Steven Spielberg', 'Warren Beatty'], 1982: ['Wolfgang Petersen', 'Steven Spielberg', 'Sydney Pollack', 'Sidney Lumet', 'Richard Attenborough'], 1983: ['Peter Yates', 'Ingmar Bergman', 'Mike Nichols', 'Bruce Beresford', 'James L. Brooks'], 1984: ['Woody Allen', 'Roland Joffe', 'David Lean', 'Robert Benton', 'Milos Forman'], 1985: ['Hector Babenco', 'John Huston', 'Akira Kurosawa', 'Peter Weir', 'Sydney Pollack'], 1986: ['David Lynch', 'Woody Allen', 'Roland Joffe', 'James Ivory', 'Oliver Stone'], 1987: ['Bernardo Bertolucci', 'Adrian Lyne', 'John Boorman', 'Norman Jewison', 'Lasse Hallstrom'], 1988: ['Barry Levinson', 'Charles Crichton', 'Martin Scorsese', 'Alan Parker', 'Mike Nichols'], 1989: ['Woody Allen', 'Peter Weir', 'Kenneth Branagh', 'Jim Sheridan', 'Oliver Stone'], 1990: ['Francis Ford Coppola', 'Martin Scorsese', 'Stephen Frears', 'Barbet Schroeder', 'Kevin Costner'], 1991: ['John Singleton', 'Barry Levinson', 'Oliver Stone', 'Ridley Scott', 'Jonathan Demme'], 1992: ['Clint Eastwood', 'Neil Jordan', 'James Ivory', 'Robert Altman', 'Martin Brest'], 1993: ['Jim Sheridan', 'Jane Campion', 'James Ivory', 'Robert Altman', 'Steven Spielberg'], 1994: ['Woody Allen', 'Quentin Tarantino', 'Robert Redford', 'Krzysztof Kieslowski', 'Robert Zemeckis'], 1995: ['Chris Noonan', 'Tim Robbins', 'Mike Figgis', 'Michael Radford', 'Mel Gibson'], 1996: ['Anthony Minghella', 'Joel Coen', 'Milos Forman', 'Mike Leigh', 'Scott Hicks'], 1997: ['Peter Cattaneo', 'Gus Van Sant', 'Curtis Hanson', 'Atom Egoyan', 'James Cameron'], 1998: ['Roberto Benigni', 'John Madden', 'Terrence Malick', 'Peter Weir', 'Steven Spielberg'], 1999: ['Spike Jonze', 'Lasse Hallstrom', 'Michael Mann', 'M. Night Shyamalan', 'Sam Mendes'], 2000: ['Stephen Daldry', 'Ang Lee', 'Steven Soderbergh', 'Ridley Scott', 'Steven Soderbergh'], 2001: ['Ridley Scott', 'Robert Altman', 'Peter Jackson', 'David Lynch', 'Ron Howard'], 2002: ['Rob Marshall', 'Martin Scorsese', 'Stephen Daldry', 'Pedro Almodovar', 'Roman Polanski'], 2003: ['Fernando Meirelles', 'Sofia Coppola', 'Peter Weir', 'Clint Eastwood', 'Peter Jackson'], 2004: ['Martin Scorsese', 'Taylor Hackford', 'Alexander Payne', 'Mike Leigh', 'Clint Eastwood'], 2005: ['Ang Lee', 'Bennett Miller', 'Paul Haggis', 'George Clooney', 'Steven Spielberg'], 2006: ['Alejandro Gonzaalez Inarritu', 'Clint Eastwood', 'Stephen Frears', 'Paul Greengrass', 'Martin Scorsese'], 2007: ['Julian Schnabel', 'Jason Reitman', 'Tony Gilroy', 'Paul Thomas Anderson', 'Joel Coen', 'Ethan Coen'], 2008: ['David Fincher', 'Ron Howard', 'Gus Van Sant', 'Stephen Daldry', 'Danny Boyle'], 2009: ['James Cameron', 'Quentin Tarantino', 'Lee Daniels', 'Jason Reitman', 'Kathryn Bigelow'], 2010: ['Darren Aronofsky', 'David O. Russell', 'David Fincher', 'Ethan Coen', 'Joel Coen', 'Tom Hooper']}
winners = {1931: ['Norman Taurog'], 1932: ['Frank Borzage'], 1933: ['Frank Lloyd'], 1934: ['Frank Capra'], 1935: ['John Ford'], 1936: ['Frank Capra'], 1937: ['Leo McCarey'], 1938: ['Frank Capra'], 1939: ['Victor Fleming'], 1940: ['John Ford'], 1941: ['John Ford'], 1942: ['William Wyler'], 1943: ['Michael Curtiz'], 1944: ['Leo McCarey'], 1945: ['Billy Wilder'], 1946: ['William Wyler'], 1947: ['Elia Kazan'], 1948: ['John Huston'], 1949: ['Joseph L. Mankiewicz'], 1950: ['Joseph L. Mankiewicz'], 1951: ['George Stevens'], 1952: ['John Ford'], 1953: ['Fred Zinnemann'], 1954: ['Elia Kazan'], 1955: ['Delbert Mann'], 1956: ['George Stevens'], 1957: ['David Lean'], 1958: ['Vincente Minnelli'], 1959: ['William Wyler'], 1960: ['Billy Wilder'], 1961: ['Jerome Robbins', 'Robert Wise'], 1962: ['David Lean'], 1963: ['Tony Richardson'], 1964: ['George Cukor'], 1965: ['Robert Wise'], 1966: ['Fred Zinnemann'], 1967: ['Mike Nichols'], 1968: ['Carol Reed'], 1969: ['John Schlesinger'], 1970: ['Franklin J. Schaffner'], 1971: ['William Friedkin'], 1972: ['Bob Fosse'], 1973: ['George Roy Hill'], 1974: ['Francis Ford Coppola'], 1975: ['Milos Forman'], 1976: ['John G. Avildsen'], 1977: ['Woody Allen'], 1978: ['Michael Cimino'], 1979: ['Robert Benton'], 1980: ['Robert Redford'], 1981: ['Warren Beatty'], 1982: ['Richard Attenborough'], 1983: ['James L. Brooks'], 1984: ['Milos Forman'], 1985: ['Sydney Pollack'], 1986: ['Oliver Stone'], 1987: ['Bernardo Bertolucci'], 1988: ['Barry Levinson'], 1989: ['Oliver Stone'], 1990: ['Kevin Costner'], 1991: ['Jonathan Demme'], 1992: ['Clint Eastwood'], 1993: ['Steven Spielberg'], 1994: ['Robert Zemeckis'], 1995: ['Mel Gibson'], 1996: ['Anthony Minghella'], 1997: ['James Cameron'], 1998: ['Steven Spielberg'], 1999: ['Sam Mendes'], 2000: ['Steven Soderbergh'], 2001: ['Ron Howard'], 2002: ['Roman Polanski'], 2003: ['Peter Jackson'], 2004: ['Clint Eastwood'], 2005: ['Ang Lee'], 2006: ['Martin Scorsese'], 2007: ['Ethan Coen', 'Joel Coen'], 2008: ['Danny Boyle'], 2009: ['Kathryn Bigelow'], 2010: ['Tom Hooper']}
### 1A: Create dictionary with the count of Oscar nominations for each director
nom_count_dict = {}
for year,name_list in nominated.items():
for name in name_list:
if name not in nom_count_dict:
nom_count_dict[name]=1
else:
nom_count_dict[name] += 1
# Add your code here
print("nom_count_dict = {}\n".format(nom_count_dict))
### 1B: Create dictionary with the count of Oscar wins for each director
win_count_dict = {}
# Add your code here
for year,name_list in winners.items():
for name in name_list:
if name not in win_count_dict:
win_count_dict[name]=1
else:
win_count_dict[name]+=1
print("win_count_dict = {}".format(win_count_dict))
六、函數(shù)
計(jì)算圓柱體的體積:
def cylinder_volume(height,radius):
pi=3.14159
return height * pi * radius**2
cylinder_volume(25,34)
1、函數(shù)主體是在頭部行之后縮進(jìn)的代碼。在此例中是定義 π 和返回體積的兩行代碼。
2、在此主體中,我們可以引用參數(shù)并定義新的變量,這些變量只能在這些縮進(jìn)代碼行內(nèi)使用。
3、主體將經(jīng)常包括 return 語(yǔ)句,用于當(dāng)函數(shù)被調(diào)用時(shí)返回輸出值。return 語(yǔ)句包括關(guān)鍵字 return,然后是經(jīng)過(guò)評(píng)估以獲得函數(shù)輸出值的表達(dá)式。如果沒(méi)有 return 語(yǔ)句,函數(shù)直接返回 None(例如內(nèi)置 print() 函數(shù))。
lambda表達(dá)式:

Lambda 函數(shù)的組成部分:
- 關(guān)鍵字 lambda 表示這是一個(gè) lambda 表達(dá)式。
- lambda 之后是該匿名函數(shù)的一個(gè)或多個(gè)參數(shù)(用英文逗號(hào)分隔),然后是一個(gè)英文冒號(hào) :。和函數(shù)相似,lambda 表達(dá)式中的參數(shù)名稱(chēng)是隨意的。
- 最后一部分是被評(píng)估并在該函數(shù)中返回的表達(dá)式,和你可能會(huì)在函數(shù)中看到的 return 語(yǔ)句很像。
- 鑒于這種結(jié)構(gòu),lambda 表達(dá)式不太適合復(fù)雜的函數(shù),但是非常適合簡(jiǎn)短的函數(shù)。
七、腳本編寫(xiě)

- 第三方庫(kù):
使用 pip (軟件包管理器)安裝庫(kù)
另一個(gè)熱門(mén)的管理器是 Anaconda,該管理器專(zhuān)門(mén)針對(duì)數(shù)據(jù)科學(xué)。
*requirements
大型 Python 程序可能依賴(lài)于十幾個(gè)第三方軟件包。為了更輕松地分享這些程序,程序員經(jīng)常會(huì)在叫做 requirements.txt 的文件中列出項(xiàng)目的依賴(lài)項(xiàng)
beautifulsoup4==4.5.1
bs4==0.0.1
pytz==2016.7
requests==2.11.1
*上邊的示例文件的每行包含軟件包名稱(chēng)和版本號(hào)。版本號(hào)是可選項(xiàng),但是通常都會(huì)包含。
課外學(xué)習(xí)補(bǔ)充
1、print不換行
#輸出的內(nèi)容后,不換行。
print("hannah" end" love ")
print("hannah")
2、打印九九乘法表
row = 1
while row <= 9:
col = 1
while col <= row:
print("%d * %d = %d" %(row,col,row * col),end=" ")
col +=1
print("")
row +=1
3、轉(zhuǎn)義字符
- \t:垂直對(duì)齊
print("1 \t 2 \t 3")
print("10 \t 20 \t 30")
- \n:換行
- \ ":添加引號(hào)
- \r:回車(chē)
