《三天搞定Python基礎概念之第一天》中文版

前言:
首先,非常感謝Jiang老師將其分享出來!本課件非常經典!
經過筆者親測,竟然確實只要三天,便可管中窺豹洞見Python及主要庫的應用。實屬難得誠意之作!
其次,只是鑒于Jiang老師提供的原始課件用英文寫成,而我作為Python的愛好者計算機英文又不太熟練,講義看起來比較慢,為了提高自學課件的效率,故我花了點時間將其翻譯成中文,以便將來自己快速復習用。
該版僅用于個人學習之用。
再次,譯者因工作中需要用到數據分析、風險可視化與管理,因此學習python,翻譯水平有限,請諒解。
在征得原作者Yupeng Jiang老師的同意后,現在我將中文版本分享給大家。

作者:Dr.Yupeng Jiang

翻譯:Murphy Wan

大綱( Outline)

  • 第1天:Python和科學編程介紹。 Python中的基礎知識: - 數據類型 - 控制結構 - 功能 - I/O文件
  • 第2天:用Numpy,Scipy,Matplotlib和其他模塊進行計算。 用Python解決一些數學問題。
  • 第3天:時間序列:用Pandas進行統計和實際數據分析。 隨機和蒙特卡羅。

------------------------------以下為英文原文-------------------------------------

  • Day 1: Introduction to Python and scientific programming. Basics in Python: data type, contro structures, fu nctions, l/O file.
  • Day 2: Computation with Numpy, Scipy, Matplotlib and other modules. Solving some maths problems with Python.
  • Day 3: Time series: statistics and real data analysis with Pandas. Stochastics and Monte Carlo.

第一天的主要內容

  • 為【零基礎】的人設計,帶你串一遍Python的基本操作。若你已經get了Python的基礎知識,請直接去第二天的內容 (傳送門-->第二天)

  • Python的背景

  • Python基礎知識

  • 控制結構

  • 功能

  • 讀/寫文件

  • 實驗部分

為什么使用Python ( Why Python?)

  • Python是開源的,這意味著它是免費的。
  • Python是一種膠水語言:
    • Python使你的編碼更加輕松
    • Python平均來講,比一些語言計算更快,比如Matlab
  • Python有一個很大的程序員社區。 它帶來了與大量的標準庫和擴展包。
  • Python廣泛應用于各種行業(Google,NASA,對沖基金,銀行等)。

使用Python 2或3?

  • Python 3不能向后兼容Python 2,這意味著Python 2中的某些軟件包或庫無法在Python 3中使用。
  • 然而,許多機構仍在使用Python 2,因為仍然有幾個軟件包與Python 3不兼容。
  • Python 2.x是歷史遺留物,而現在,Python 3.x是該語言的未來。 2010年年中,2.7版本的2.7版本將不會再出現新的主要版本。
  • 我們會遇到一些差異,但不會太多。
  • 檢查https://wiki.python.org/moin/Python2 或Python3或其他在線資源獲取更多信息

一些在線資源 (Some online resources)

Python環境 (Python environment)

  • 安裝Python科學堆棧的推薦方法是使用Continuum Analytics Anaconda。
  • Anaconda是一個免費的軟件包管理器,環境管理器,以及開源軟件包的集合。
  • Anaconda包括核心Python解釋器和標準庫。
  • https://www.continuum.io/downloads

Anaconda中包括的庫(Libararies)

管理你的Anaconda

你可以在本課程中學到什么?

  • 本課程是為初學者設計的。 它不需要任何以前的任何編程語言的知識。
  • Python編程的基礎知識。
  • 使用Numpy,Scipy和Sympy進行數學計算。
  • 使用Matplotlib庫繪制圖形。
  • 與Pandas分析實際數據和時間序列。
  • 學習如何使用它作為工具。

今天的安排

  • 早上:Python編程基礎介紹。 在上午的會議中,您將需要做一些練習。 只是一些熱身水平的問題,他們會給你一個關于Python編程的想法。
  • 下午:半小時內完成介紹部分。 那么我們會有三個大問題要解決。 他們將是今天的一個很好的總結:講座。 你將有一個小時獨立工作。 然后,我將在過去半小時內提供分析和解決方案。

練習1

  • 安裝Anaconda并更新它以便擁有 所有包的最新版本。 我們將使用Python 3.4(而不是以前的Python 2.7版本)。

  • 通過鍵入以下命令啟動Spyder并計算76:

    x = 7 ** 6 打?。▁)

  • 啟動IPython Notebook并計算7的6次方

縮進(Indentation)

  • 在某些語句之后,會加一個縮進; 縮進減少,則表示當前塊結束。
  • 例如
    x = 7 ** 6
    print(x)#witt. fron't inden-tation
  • 這段代碼在Python中是錯誤的,雖然它在C ++,Matlab和許多其他代碼或應用程序中是可以接受的。

編程中的一些好習慣(Some good habit in programming)

  • 在需要縮進和換行的地方使用這個功能;不要把你的腳本弄亂了。
  • 不要使用沒有意義的變量;要用可以被描述的變量。
  • 寫注釋。 幫助別人和自己在以后理解你現在所寫的代碼內容。
  • 不要同時開始學習多種編程語言。

關于Python的基礎知識(Basic knowlegde on Python)

常用的數字數據類型(Common used numeric data types)

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運算將導致浮點數。

算數運算符(Arithmetic operators)

Name Notation Examples
Addition + a + b
Subtraction - c - b
Multiplication * x*y
Division / x/z
Modulus % x%a
Exponent ** a**x

練習2(Exercise 2)

  • 猜下面代碼的結果。執行他們,看答案。
  • Try to guess the results of the following code. Implement them and check your answers.
  • 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

浮點數的精度(Precision of float)

  • 嘗試在您的控制臺中鍵入0.1 + 0.2。 你會發現這個值是
  • 0.30000000000000004
  • 這是二進制浮點的本質。 您可以在支持硬件浮點運算的所有語言中看到同樣的東西。
  • 可以使用“round()”功能控制顯示精度,但也有上述情況,這意味著round(9.995,2)返回9.99而不是10,因為9.995的存儲稍小于9.995。
  • decimal Library將給出精確的存儲值,請參見以下示例。

例子(Example)

import  decimal  
# import  the  libray  "decimal"    
# display  2  decimal  precision
print (round (3*1415 ,   2))   #  result  3. 14
print (round (9 .995 ,   2))   #  result  9. 99

#call   function   "Decimal "  from lib "decimal"
print (decimal.Decimal (9.995))
The last "print" returns
9.9949999999999992184029906638897955417633056640625,
which is exactly how 9.995 is stored in the hardware.

練習3:字符串str的一些功能(Exercise3:Some functions for 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.find('in')) # index of 'i' in 'in'
print(t.find('Python')) # find sth not in
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
    He is a string. who are you?    
    ['He', 'is', 'a', 'string.', 'Who', 'are', 'you?']    
    11    
    -1    
    He i    
    He|is|a|string.|Who|are|you?    
    www.google.com    

Python功能:索引(Python features: Indexing)

  • Python具有與C ++類似的索引規則,其起始索引為0。
  • 當通過索引返回值時,間隔實際上是[,]樣式,這意味著不包括終端索引。

基本的數據結構(Basic data structures)

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)是對象中唯一的無序集合對象。

列表的一些有用功能(Some useful functions for list)


l = [1, 2, 3.14, 'data'] #list
print (type(l))l.append ([4,  3])
print(l)l.extend (['delta' ,5 ,6] )   #add  a  list
print(l)l.insert(3, 'beta')  #insert  before  index 3
print(l)l.remove ('data')   #delete an elementprint(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 features: Refer for object)

  • 在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]

多維列表(Multidimensional list)

  • 我們可以創建一個包含多行的列表
a  =  [[1,2 , 3 ,4],[1,2 ,3,4],[1,2 ,3]] 
print(a)
print(a[0][3])
  • 但請注意:
    多維列表不是矩陣。 數學運算符可能會導致您不想看到的結果。 對于矩陣計算,我們將在明天花費大量的時間。

條件語句(Conditions)

  • 條件控制元素包括if,else和elif。
  • 對于條件語句,我們有如下幾種:
Name Notation
larger >
smaller <
equal ==
larger or equal >=
sma
  • 對于多條件同時使用的情況,我么使用and, or 或者 not作為關鍵字來相互銜接

示例和練習:條件語句 (Example & exercise: conditions)

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 !!!

循環語句 (Loops)

  • 循環語句有很多不同的樣式代碼,我們只提供兩個常用的語句。
     for...in ... :statement A
     是循環中最常用的語句,通常與range(start,end,step)一起使用,start為起始值,end為結束值,step為步長。 例如,                
     range(0,8,1)  給出[0,1,2,3,4,5,6,7]

2/                     
        while ...:statement A        
     將會執行A語句,直到滿足while的條件。

舉例:循環語言(Example: loops)

# for和range的例子 example  of  for  and  range  
# 初始值默認值為default start of range is O     
# 步長默認值為default step of range is 1     
for i in range(2, 10, 3):         
    print(i)         
    l= i**2         
    print(l)

# white to sum   up 1 to 100
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.
# search the first
# be divided by 17
for i in range(300, 351):
    if i % 17 == O:
        print (i)
        break
    else :
        cantinue

循環語句嵌套(Loop inside the loop)

  • 循環語句可以內嵌在另一個循環語句中(Loop can be written inside another loop)
for  i  in range (10):
     print (i)     
     for j in range (5):
         print (j)

練習(Exercises)

  • 計算從1到1000的累計值。
  • 計算從1到1000的偶數之和。

功能 (Functions)


功能(方法or函數)的聲明 (Function declaration)

  • 方法定義如下(Functions are defined as)
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)

默認參數

  • Python中的函數沒有函數重載(function overloading)。 這意味著你不能有兩個共享同名的功能。 但是操作符重載(operator overloading)是正常的。
  • 您可以為函數的參數提供默認值,例如。
   def MaxOfTwo(xl, x2 = 1): ...
  • 請將您的默認參數放在一堆函數參數的末尾處。

具有兩個輸出的函數(方法)

  • 函數還可以返回兩個或多個輸出。 在這種情況下,你應該這樣寫出代碼:
def  f (x1, x2,  x3, ...):
     ......
     return(y1,  y2,  y3, ...)

a1,b1,c1 = f(...)

讀取/寫入文件 (Reading/ writing files)


內建open()方法 [Built-in open() function]

  • 要打開一個文件,使用Python內建的open()函數。 open()方法返回一個文件對象,最常用的一般使用兩個參數。
file_object = open(filename, mode)
  • 這個mode參數可以是(The mode can be)
    • 'r' 只讀模式(when the file will only be read)
    • 'w' 只寫模式(與一個現存文件文件同名,則被清除)
    • 'a' 添加模式,即任意寫入文件的數據都被自動添加到末尾
    • 'r+' 打開文件,可以讀、寫

創建一個文件 (Creating new file)

   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()

讀取一個文件 (Reading a file)


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()


循環讀取一個文件 (Looping over a file object)


file = open('newfile.txt', 'r')
for  line  in  file:
     print (line)
file.close()

輸出將是
        我是為這個課程而誕生的
        你怎么樣?你的考試如何

* ------以下是英文原文--------------------
Output would be:
          I am created for the course   
          How about you? How is your exam?


增加一個文件 (Adding in a file)

file = open('newfile.txt', 'a')
file.write('\nI am back again. \n')
file.write('Do  you miss me?\n')
file.clase()

with語句 (The with statement)

  • 很容易忘記關閉{close()}文件。 由于這個和其他原因,最好使用with語句:

with open(“humpty.txt”) as f:

  • 這樣可以確保文件正確關閉,即使讀取時發生錯誤。


文件路徑 (File paths)

  • 也可以使用絕對路徑指定文件名。
  • 示例(Mac / Linux):
open ('/etc/gimp/2.O/gtkrc')
  • 示例(Windows):
open('C:\Users\user\Documents\file.txt')
  • 請注意,反斜杠需要轉義(寫入兩次'\')


實驗部分 (Lab Session)



目標1 (Target 1)

  • 您的老板要求您編寫一段代碼,以便對于具有float或int類型元素的任何長度列表(list),您的函數可以將它們按照從大到小排序。

  • 例如 如果你的老板給一個list

               [8, 2, 4, 6, 1, 9, 0, 3, 5, 7]

  • 你的方法將返回
               [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]



目標1提示: (Hint for Target 1:)

  • 有三種不同的排序算法:

    • 氣泡排序:從最后開始,將最后兩次的最大值傳遞給前一個索引。 你第一次遍歷每一個數字,你通過最大的數字到一開始。 然后你在剩下的數字中重復一遍。
    • 選擇排序:首先搜索整個列表。 并將最小的數字傳遞到列表的末尾。 然后搜索整個列表排除最后一個數字。 再重復該步驟。
    • 插入排序:從一開始,按順序比較第一個數字和第二個數字,將第一個數字交換為最大數字。 然后重復它構成第二個直到結束。

-----以下為英文原文-----

There are three different algorithms of sorting:

  • Bubble sort: Starting from the end, pass the maximum of last two to the former index. The first time you traverse every number, you pass the largest number to the beginning. Then you repeat them in the rest numbers.
  • Selectian sort: Search the whole list first. And pass the smallest number to the end af the list. Then search the whole list exclude the last number. Repeat it.
  • Insert sort: Starting from the beginning, compare the first number and the rest sequentially to swap the first number to be the biggest. Then repeat it fram the second one until end


目標2 (Target 2)

  • 代碼功能

    • 3days_img01.gif
  • 使用派生詞的定義,對其數字導數函數進行編碼。

  • 找到數值解

    • 3days_img02.gif

通過二等分法。



目標2的提示 (Hint for Target 2:)

  • 衍生物可以近似于

    • 3days_img04.gif
  • 3days_img05.gif
  • 3days_img06.gif
  • 二分法實現如下:
    • 給出間隔[a,b],使得f(a)和f(b)具有不同的符號。
    • 計算中點c = 0.5 (a + b)和中點f(c)的函數值。
    • 如果f(x)足夠,則停止。 否則,將(a,f(a))或(b,f(b))替換為(c,f(c)),以便在新間隔內存在過零點

-----以下為英文原文-----

  • The derivative can be appraximated by

    • f'(x) ≈ [f(x + h) - f (x)]/h,
    • f'(x) ≈ [f(x + h) - f(x - h)]/h,
    • f'(x) ≈ [f(x+h) - f (x-h)]/2h
  • Bisection is implemented as:

    • Give an interval [a, b] such that f(a) and f(b) have different sign.
    • Calculate the midpoint c= 0.5 * (a + b) and the functian value at the midpoint, f(c).
    • If f(x) is goad enough, stop. Otherwise replace either (a, f(a)) or (b, f(b) with (c, f(c)) so that there is a zero crossing within the new interval


目標3 (Target 3)

  • 在面試時 ,你的面試官者要求你編寫一個可以給他第n個斐波納契數字的函數,其中n由你的面試官決定。

  • In your interview. your interviewer ask yau to code a function that could give him the n-th Fibonacci number, where n is determined by your interviewer.


目標3提示: (Hint for Target 3:)

  • 斐波那契序列如下

    • 3days_img07.gif
    • 3days_img08.gif
  • 其中一個方法是遞歸地使用一個函數。

  • 其中一個方法是利用append()函數。

-----以下為英文原文-----

  • Fibonacci sequence is given like

    ao = 1, a1 = 1,

    an = an-1 + an-2 for n> 2

  • One of the method is to recursively use a function.* One of the method is to take advantage from append() function.


第一天的課程到此結束,辛苦了

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容