1. 程式人生 > >Python 基礎系列--開篇

Python 基礎系列--開篇

學習 Python 的過程讓我產生了以下改變

  1. 找回當初選擇計算機的初心
  2. 開始主動學習,關注新技術
  3. 嘗試編寫程式提高重複工作的效率
  4. 編碼側重可讀性和效能
  5. 分享己學知識和感悟,尋找志同道合的朋友

Python 能帶給我的,同樣也能帶給你,於是我決定嘗試寫一些 Python 基礎系列文章,帶你入門 Python,達到能使用 Python 解決日常問題的目的。同時也希望 Python 這門語言能帶給你學習和編碼的快樂。

如果不是基於以上目的,那麼你仍有理由學習程式設計,學習 Python,原因如下:

李開復老師說過:“人工智慧將快速爆發,十年後 50% 的人類工作將被 AI 取代”。 華爾街的交易員,這個曾經很光鮮的職業很快消失了;未來的保安也會部分消失,因為攝像頭的監控,加上一些機器人巡視,已經不需要保安了;司機可能也會消失,還包括一些非常高階的白領,比如說放射科醫生,他們的看片能力不如機器人。

可以思考一下,自己的工作在十年後是否會被人工智慧取代,如果會,如何才能體現自己的價值呢 ?不妨從現在起就要開始做一些機器不能做的事情,一些人機結合的事情,比如程式設計,它是一門技術,也是一門藝術,而且人工智慧最親近的語言就是 Python ,所有語言當中,Python 是最接近人類思維的,程式碼的風格也是人類可讀的, 比其他語言更易學,易用。常言道:人生苦短,我用 Python。

如果你決定開始學習 Python,請繼續往下看。

1. 關於版本選擇

Python 目前有兩個版本 Python2 和 Python3,最新版本分別是 Python2.7.15 和 Python3.7.0 。 Python2 即將停止更新,第三方的庫也會全部移植到 Python3,Python3 做了更多優化,可以說 Python3 是未來,初學者可以直接選擇 Python3 來學習,其實根本不用糾結學習 Python2 和 Python3,他們的語法幾乎沒有差別。

2. 安裝 Python 環境

3. 瞭解 Python 的直譯器

Python 是開源的,任何人,只要你夠厲害,你都可以編寫 Python 的直譯器。

CPython:是官方版本的直譯器,使用 C 語言編寫,因此叫 CPython 。從官方下載的安裝包安裝後,我們就獲得了 CPython 直譯器,也是使用最廣泛的直譯器,本系列所有程式碼也都在 CPython 下執行。

IPython:不是正在意義上的直譯器,仍使用 CPython,只不過加了一層外殼,使執行結果在字元介面看起來更美觀,如果你喜歡互動式環境下進行資料分析,可以使用這個。CPython 用 >>> 作為提示符,而 IPython用 In [序號]: 作為提示符。

PyPy:是使用 Python 實現的 Python 直譯器,提供了 JIT 編譯器和 沙盒 功能,目的是做到 動態編譯 因此執行速度比 CPython 要快。絕大部分 Python 程式碼都可以在 PyPy 下執行,但是 PyPy 和 CPython 有一些是不同的,這就導致相同的 Python 程式碼在兩種直譯器下執行可能會有不同的結果。如果你的程式碼要放到PyPy 下執行,就需要了解 PyPy 和 CPython 的不同點。

Jython:是使用 Java 實現 Python 直譯器,可以直接把 Python 程式碼編譯成 Java 位元組碼執行。

IronPython:是執行在微軟 .Net 平臺上的 Python 直譯器,可以直接把 Python 程式碼編譯成 .Net 的位元組碼。

對於初學者,使用 CPython 已經足夠,其他直譯器,做到了解即可。

4. 關於開發工具選擇

有很多人包括我,在最開始階段總是糾結使用哪個工具:

  • 使用 vim 還是 emacs 還是 ue ?
  • 使用 eclipse 還是 pycharm ? 這裡我想說的是,工具它一點都不重要,也不會特別提高你編碼效率,程式設計,耗時的是你思考的過程,而不是寫程式碼的過程,你完全可以使用 Python 自帶的 ide 或簡單的記事本編寫 Python 程式碼,然後在命令視窗執行:
python filename.py

即可。但是如果你碰巧會某個編輯工具或 開發工具,那麼就使用它好了,如果沒有使用過什麼開發工具,那麼請選擇 Pycharm 社群版本(免費),它是最好的 Python 程式設計工具,沒有之一。

5. 從科學計算器開始

程式設計是將問題資料化的一個過程,資料離不開數字,Python 的數字運算規則和我們在小學初中學習的四則運算規則是一樣的,即使不使用 Python 來編寫複雜的程式,也可以把它當作一個強大的科學計算器。初學者可以使用 Python 來代替你的計算器,先感覺下 Python 的魅力,命令視窗輸入 Python 回車後進入互動式環境,如下所示:

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

常見的科學計算如下

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # 總是返回一個浮點數
1.6
>>> 19 / 3  # 整數除法返回浮點型
6.333333333333333
>>>
>>> 19 // 3  # 整數除法返回向下取整後的結果
6
>>> 17 % 3  # %操作符返回除法的餘數
1
>>> 5 * 3 + 2.0 
17.0

Python 可以使用**操作來進行冪運算:

>>> 5 ** 2  # 5 的平方
25
>>> 2 ** 7  # 2的7次方
128

在互動模式中,最後被輸出的表示式結果被賦值給變數 _ 。這能使您在把Python作為一個桌面計算器使用時使後續計算更方便,例如:

>>> 1+2
3
>>> _+3
6
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

Python 數字型別轉換:

>>> int(1.2) #將一個浮點資料轉換為整數
1
>>> int(1.6)  #將一個浮點資料轉換為整數
1
>>> int("4")  #將一個整數字符串轉換為整數
4
>>> float(2)
2.0
>>> complex(2) #將x轉換到一個複數,實數部分為 x,虛數部分為 0。
(2+0j)
>>> complex(2,3) # 將 x 和 y 轉換到一個複數,實數部分為 x,虛數部分為 y。x 和 y 是數字表達式
(2+3j)
>>>

常用的數學函式如下表格所示:

函式 返回值(描述)
abs(x) 返回數字的絕對值,如abs(-10)返回10
ceil(x) 返回數字的上入整數,如math.ceil(4.1)返回5
exp(x) 返回e的x次冪(ex),如math.exp(1)返回2.718281828459045
fabs(x) 返回數字的絕對值,如math.fabs(-10)返回10.0
floor(x) 返回數字的下舍整數,如math.floor(4.9)返回4
log(x) 如math.log(math.e)返回1.0,math.log(100,10)返回2.0
log10(x) 返回以10為基數的x的對數,如math.log10(100)返回2.0
max(x1,x2,…) 返回給定引數的最大值,引數可以為序列。
min(x1,x2,…) 返回給定引數的最小值,引數可以為序列。
modf(x) 返回x的整數部分與小數部分,兩部分的數值符號與x相同,整數部分以浮點型表示。
pow(x,y) x**y運算後的值。
round(x[,n]) 返回浮點數x的四捨五入值,如給出n值,則代表舍入到小數點後的位數。
sqrt(x) 返回數字x的平方根。

7. 使用 help 方法獲取 Python 的幫助

在 Python 的世界裡,一切都是物件,你可以定義一個變數,在使用這個變數時,你可能需要知道它有哪些方法,你不可能記憶所有的方法,但你可以通過 help(類名/物件名) 檢視其幫助資訊,以便快速選用你需要的方法。

例如,定義一個字串,我想知道 python 提供的字串方法有哪些,可以這樣做:

>>> a="hello,world,hello,python"  #定義了一個字串
>>> type(a)  #檢視其變數的型別
<class 'str'>
>>> help(str)  #檢視 str 類的幫助資訊
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |
 |  Methods defined here:
 |
 |  __add__(self, value, /)
 |      Return self+value.
 |
 |  __contains__(self, key, /)
 |      Return key in self.

......

 |
 |  rjust(...)
 |      S.rjust(width[, fillchar]) -> str
 |
 |      Return S right-justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space).
 |
 |  rpartition(...)
 |      S.rpartition(sep) -> (head, sep, tail)
 |
 |      Search for the separator sep in S, starting at the end of S, and return
 |      the part before it, the separator itself, and the part after it.  If the
 |      separator is not found, return two empty strings and S.
 |
 |  rsplit(...)
 |      S.rsplit(sep=None, maxsplit=-1) -> list of strings
 |
 |      Return a list of the words in S, using sep as the
 |      delimiter string, starting at the end of the string and
 |      working to the front.  If maxsplit is given, at most maxsplit
 |      splits are done. If sep is not specified, any whitespace string
 |      is a separator.
 |
 |  rstrip(...)
 |      S.rstrip([chars]) -> str
 |
 |      Return a copy of the string S with trailing whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |
 |  split(...)
 |      S.split(sep=None, maxsplit=-1) -> list of strings
 |
 |      Return a list of the words in S, using sep as the
 |      delimiter string.  If maxsplit is given, at most maxsplit
 |      splits are done. If sep is not specified or is None, any
 |      whitespace string is a separator and empty strings are
 |      removed from the result.
 |

......

 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |
 |  maketrans(x, y=None, z=None, /)
 |      Return a translation table usable for str.translate().
 |
 |      If there is only one argument, it must be a dictionary mapping Unicode
 |      ordinals (integers) or characters to Unicode ordinals, strings or None.
 |      Character keys will be then converted to ordinals.
 |      If there are two arguments, they must be strings of equal length, and
-- More  --

從上面的幫助資訊中我們看到有個 split 方法可以分割字串,可以返回一個列表,呼叫下試試看:

>>> a.split(",")
['hello', 'world', 'hello', 'python']
>>> type(a.split(","))
<class 'list'>
>>> help(list)
Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |
 |  Methods defined here:
 |
 |  __add__(self, value, /)
 |      Return self+value.
 |

......

 |
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |
 |  insert(...)
-- More  --

這裡我們看到了關於 list 這個類,Python 提供的所有方法,可以直接呼叫,例如統計列表中單詞 hello 的個數:

>>>a="hello,world,hello,python"
>>> a.split(",").count("hello")
2

關於類中變數或方法的識別符號號說明 (1)_xxx      "單下劃線 " 開始的成員變數叫做保護變數,意思是隻有類例項和子類例項能訪問到這些變數, 需通過類提供的介面進行訪問;不能用’from module import *'匯入。 (2)__xxx    類中的私有變數/方法名 (Python的函式也是物件,所以成員方法稱為成員變數也行得通。), " 雙下劃線 " 開始的是私有成員,意思是隻有類物件自己能訪問,連子類物件也不能訪問到這個資料。 (3)__xxx__ 系統定義名字,前後均有一個“雙下劃線” 代表python裡特殊方法專用的標識,如__init__()代表類的建構函式。

如果暫時看不懂可以先不理會這些,主要是學會使用 help(obj) 函式 來獲取關於類的最專業的幫助資訊,這裡不聯網也可以使用,不需要查搜尋引擎,養成這個習慣,可以讓你在編碼過程中保持專注

7. 使用瀏覽器檢視 Python 的幫助

如果你不喜歡在字元介面檢視幫助資訊,你可以使用瀏覽器來檢視,命令如下

呼叫瀏覽器命令

瀏覽器介面如下所示: 使用瀏覽器檢視 Python 的幫助文件

這裡可以檢索模組的幫助資訊,非常方便和直觀,建議你經常使用這個,而不是搜尋引擎,防止某度會轉移的你稀缺的注意力資源。 (完)

如果您覺得這篇文章幫助,請點贊、轉發。公眾號搜尋 somenzz 或掃下二維碼關注。  somenzz 的公眾號