本文內容來源於Yupeng Jiang(倫敦大學數學系)課件,本人認爲非常經典,原文爲純英文,網上也已經有翻譯的版本,但是自認爲還是有些凌亂,看起來不是很舒服,故再次整理髮佈於此。其一,是作爲自己鞏固複習之用;其二,資源共享
課程大綱:
- 第1天:Python背景 ;基礎(環境,數據類型 ,運算符,數據結構 ,條件語句,循環語句,方法 ,I/O)
- 第2天:用Numpy,Scipy,Matplotlib和其他模塊進行計算。 用Python解決一些數學問題。
- 第3天:時間序列:用Pandas進行統計和實際數據分析。 隨機和蒙特卡羅。
day1:
一、背景:
爲什麼使用python?
- Python是開源的,這意味着它是免費的。
- Python是一種膠水語言:
- Python使你的編碼更加輕鬆
- Python平均來講,比一些語言計算更快,比如Matlab
- Python有一個很大的程序員社區。 它帶來了與大量的標準庫和擴展包。
- Python廣泛應用於各種行業(Google,NASA,對衝基金,銀行等)。
二、基礎知識:
1.python環境
- 安裝Python科學堆棧的推薦方法是使用Continuum Analytics Anaconda。
- Anaconda是一個免費的軟件包管理器,環境管理器,以及開源軟件包的集合。
- Anaconda包括核心Python解釋器和標準庫。
- https://www.continuum.io/downloads
2. Anaconda中包含的庫:
- NumPy(http://numpy.scipy.org ):該庫用於處理(大)數組。
- SciPy(http://www.scipy.org ):該庫包含許多有用的科學功能。
- Matplotlib(http://matplotlib.sourceforge.net ):該庫用於繪圖。
- Pandas(http://pandas.sourceforge.net ):該庫有效並快速分析大數據集; 尤其針對金融時間序列。
- IPython(http://wprw.ipython.org ):shell、或基於瀏覽器:開發環境。
- Spyder(http://pythonhosted.org/spyder/ ):IDE交互式開發環境
3.常用的數據類型:
Name | Notation | Declaration e.g. |
---|---|---|
Integers | int | a = 10 |
Floating | float | b = 3.14 |
Complex | complex | c = 1 + 2j |
String | str | d = 'Python' |
- 備註:
- 在Python 2.7中,int與另一個int運算將導致int結果。 但是,一個浮點運算與int會導致浮點數。
- 在Python 3.x中,int與另一個int運算將導致浮點數。
4.算數運算符:
Name | Notation | Examples |
---|---|---|
Addition | + | a + b |
Subtraction | - | c - b |
Multiplication | * | x*y |
Division | / | x/z |
Modulus | % | x%a |
Exponent | ** | a**x |
練習:執行下列代碼
- a = 10 # int
- b = 3.14 # fLoat
- c = 3 #int
- d = a ** 2 # square of a
- print (type (d)) # return the type of d
- print (type (d/l0)) # return the type of d/l0
- print (type (a/b)) # return the type of a/b
- print (type (a/c)) # return the type of a/c
- print (type (bd)) # return the type of bd
浮點數的精度:
- 嘗試在您的控制檯中鍵入0.1 + 0.2。 你會發現這個值是
- 0.30000000000000004
- 這是二進制浮點的本質。 您可以在支持硬件浮點運算的所有語言中看到同樣的東西。
- 可以使用“round()”功能控制顯示精度,
- decimal Library將給出精確的存儲值,請參見以下示例。
import decimal print (round (3*1415,2)) #3. 14 print (round (9.995,2)) #9. 99 print (decimal.Decimal (9.995)) #9.9949999999999992184029906638897955417633056640625
練習:字符串str的一些方法
t = 'He is a string. Who are you?' print(t.capitalize()) # Cap first letter print(t.split()) # split by words print(t.find('i')) # return index of 'i' print(t[0:4]) # returu from index 0 to 3 print(t.replace(' ','|')) # replace by '|' w = 'http://www.google.com' print(w.strip('http://')) #delete sth
5.python基本數據結構
Name | Nation | Declaration e.g. |
---|---|---|
Tuple | tuple | b = (1,2.5, 'data') |
List | list | c = [1,2.5,'data'] |
Dictionary | dict | d = {'Name': 'Kobe', 'Country':'US'} |
Set | set | e = set(['u','d','ud','d','du']) |
- 元組(tuple)只有幾種方法可以更改。
- 列表(list)比元組更靈活。
- 字典(dict)是一個鍵值對存儲對象。
- 集合(set)是對象中唯一的無序集合對象。
列表(list)的一些方法:
l = [1,2,3.14,'data']
print (type(l))
l.append ([4,3])
print(l)
l.extend (['delta',5,6] )
print(l)
l.insert(3,'beta')
print(l)
l.remove ('data')
print(l)
<class 'list'> [1, 2, 3.14,'data',[4,3]] [1, 2, 3.14,'data',[4,3],'delta',5,6] [1, 2, 3.14,'beta','data',[4, 3],'delta', 5,6] [1, 2, 3.14,'beta',[4, 3],'delta',5,6]
python參考對象:
- 在Python中,如果要將值從一個對象傳遞給另一個對象,則=(等號)將按地址傳遞值。
- 例如:
x = [1,2,3,4] y = x y[0] = 5 print(x) x = [1,2,3,4] z = x.copy() z[0] = 5 print (x)
輸出:
[5,2,3,4] [1,2,3,4]
多維列表:試一試
a = [[1,2,3,4],[1,2,3,4],[1,2,3]] print(a) print(a[0][3])請注意: 多維列表不是矩陣。 數學運算符可能會導致您不想看到的結果。 對於矩陣計算,我們將在明天花費大量的時間
6.條件語句
- 條件控制元素包括if,else和elif。
- 對於條件語句,我們有如下幾種:
Name | Notation |
---|---|
larger | > |
smaller | < |
equal | == |
larger or equal | >= |
sma |
- 對於多條件同時使用的情況,我麼使用and, or 或者 not作爲關鍵字來相互銜接
a = [24,16,54] b = [] if a[0]< a[1] and a[0]< a[2] : b.append(a[0]) if a[1] < a[2]: b.append(a[1]) b.append(a[2]) else: b.append(a[2]) b.append(a[1]) # This piece of code is not done yet. # Please complete it !!!
7.循環語句:
循環語句有很多不同的樣式代碼,我們舉例說明兩種,for循環和while循環
for...in ... :
statement A
是循環中最常用的語句,通常與range(start,end,step)一起使用,start爲起始值,end爲結束值,step爲步長。
while ...:
statement A
將會執行A語句,直到滿足while的條件。
例子:for i in range(2, 10, 3): print(i) l= i**2 print(l) a = 0 sumup = O while a < 100 : a + 1 sumup += a print(sumup)
break和continue
- 你可以在循環語句中使用關鍵字break,以跳出循環。(you can use the keyword break inside a loop to leave the loop..)
- 你也可以在循環語句中使用關鍵字continue,以暫停當前循環執行後面的語句。(you can use the keyword continue inside a loop to stop pracessing the current iteration of the loop and immediately go on to the next round.)
- 舉例 E.g.
for i in range(300, 351): if i % 17 == O: print(i) break else : continue
循環嵌套:
for i in range(10): print(i) for j in range(5): print(j)
8.方法(函數)的定義
def TheNameOfFunction(paral, para2): ... return Outcome
舉例:求兩個變量最大值的函數
def MaxOfTwo (x1, x2): if x1 >= x2: return x1 else: return x2 a = l b = 2 c = MaxOfTwo(a, b) print(c)
9.讀取/寫入文件
內置的open()方法
- 要打開一個文件,使用Python內建的open()函數。 open()方法返回一個文件對象,最常用的一般使用兩個參數。
file_object = open(filename, mode)
這個mode參數可以是(The mode can be)
- 'r' 只讀模式(when the file will only be read)
- 'w' 只寫模式(與一個現存文件文件同名,則被清除)
- 'a' 添加模式,即任意寫入文件的數據都被自動添加到末尾
- 'r+' 打開文件,可以讀、寫
例子:
寫入
file = open('newfile.txt', 'w') file.write('I am created for the course. \n') file.write('How about you? ') file.write('How is your exam?') file.close()
讀取
file = open('newfile.txt', 'r') #show whole efile print(file.read()) #show first ten characterrs print(file.read(10)) #view by line print(file.readline()) #view all by line print(file.readlines()) file.close()
循環讀取
file = open('newfile.txt', 'r') for line in file: print (line) file.close()
文件添加內容
file = open('newfile.txt', 'a') file.write('\nI am back again. \n') file.write('Do you miss me?\n') file.close()
with語句
- 由於很容易忘記close文件,所以最好使用with語句:
with open("humpty.txt") as f:
...
第二天內容請進傳送門>>>三天搞定python基礎-day2