Python (1): Tutorial歸納(Python快速入門)

0 Python3.7簡介

  Python 是一門簡單易學且功能強大的編程語言。它擁有高效的高級數據結構,並且能夠用簡單而又高效的方式進行面向對象編程。Python 優雅的語法和動態類型,再結合它的解釋性,使其在大多數平臺的許多領域成爲編寫腳本或開發應用程序的理想語言。
  用 Python 編寫的程序通常比同樣的 C、C++ 或 Java 程序更短小,這是因爲以下幾個原因:

  • 高級數據結構使你可以在一條語句中表達複雜的操作;
  • 語句組使用縮進代替開始和結束大括號來組織;
  • 變量或參數無需聲明

  本文參考官方tutorial進行重點歸納總結,以供Python初學者快速入門。

1 Python解釋器

Python 解釋器通常被安裝在目標機器的/usr/local/bin/python3目錄下,通過輸入:

python3

命令啓動它。

通常你可以在主窗口輸入一個文件結束符(Unix系統是Ctrl-D,Windows系統是Ctrl-Z)讓解釋器以 0 狀態碼退出。如果那沒有作用,你可以通過輸入quit()命令退出解釋器。

  • 可執行 Python 腳本
    Unix 系統上,Python 腳本可直接執行,像 shell 腳本一樣,只需要把下面內容加入到
#!/usr/bin/env python3

(假設 python 解釋器在用戶的 PATH 中)腳本的開頭,並給予該文件的可執行模式:

chmod +x script.py

2 輸入和輸出

2.1 格式化輸出

有2種輸出方式:

  • 表達式語句
  • print()函數

① 逗號(,)輸出爲空格分隔;
② %, %s, %d等

>>> print('string format: %d %s, %d' % (1,'and',3))  
string format: 1 and, 3

③ str.format()方法:str.format(*args, **kwargs)
  輸出字符串的{}被替換。{}內容爲位置參數的數字下標或關鍵字參數名稱。
{}內可以使用:,如:{0:.3f}{1:10d}

>>> print("What's your {1}?".format(1,23,45,6,'axs',one=1,two=2,three=3)) 
What's your 23?	# positional index
>>> print("What's your {two}?".format(1,23,45,6,'axs',one=1,two=2,three=3))
What's your 2?	# keyword name
>>> print('{0:.3f}'.format(123.4567))
123.457

2.2 輸入

  • input()函數:用戶控制檯輸入。
birth = input('Birthday:')  # get a str via user input
birth = int(birth)          # change to int
if birth < 2000:
    print('00前')
else:
    print('00後')

2.3 文件讀寫

  • 打開文件
    函數open()返回文件對象。open(file, mode='r')
f = open('/home/ywq/Downloads/1.txt', 'r', encoding='gb18030')
  • 按行讀取文件內容
for eachline in f:	# eachline爲str類型
	print(eachline, end='')
  • 寫入內容
f = open(filename, 'w'):
f.write('something to write')
  • 關閉文件
    文件讀寫後要記得關閉
f.close()

3 Python流程控制

3.1 if 語句

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...      x = 0
...      print('Negative changed to zero')
... elif x == 0:
...      print('Zero')
... elif x == 1:
...      print('Single')
... else:
...      print('More')
...
More

可能會有零到多個 elif 部分,else 是可選的。if … elif … elif …序列用於替代其它語言中的 switch 或 case 語句。

3.2 for 語句

Python 的 for 語句依據任意 sequence(鏈表或字符串)中的子項,按它們在序列中的順序來進行迭代。

常用序列見本文Sequence type部分。

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12

循環技巧

  • 字典中循環時,關鍵字和對應的值可以使用 items() 方法同時解讀出來:
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave
  • 序列中循環時,索引位置和對應值可以使用 enumerate() 函數同時得到:
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

3.3 break, continue和循環中的else子句

break和continue語法和C中一樣:

  • break: 中斷該層for或while循環。
  • continue: 中斷本次循環,繼續下一次循環。

循環中的else子句:循環中可以有一個else語句,循環迭代完整個列表(對於 for )或執行條件爲 false (對於 while )時執行,但循環被 break 中止的情況下不會執行。

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

3.4 pass語句

pass語句什麼都不做。

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...

3.5 定義函數

  • 關鍵字 def 引入了一個函數 定義。
  • 在其後必須跟有函數名和包括形式參數的圓括號。
  • 函數體語句從下一行開始,必須是縮進的。
  • return 語句從函數中返回一個變量、返回多個變量時類型爲tuple,不帶表達式的 return 返回 None
>>> def fib2(n): # return Fibonacci series up to n
...     """Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while a < n:
...         result.append(a)    # see below
...         a, b = b, a+b
...     return result
...
>>> f100 = fib2(100)    # call it
>>> f100                # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

3.5.1 默認參數

  • 爲一個或多個參數指定默認值。這會創建一個可以使用比定義時允許的參數更少的參數調用的函數,
  • 函數引用的實際參數在函數調用時引入局部符號表,因此,實參總是引用傳遞

3.5.2 關鍵字參數

函數可以通過 關鍵字參數 的形式來調用,形如 keyword = value.

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

接受一個必選參數 (voltage) 以及三個可選參數 (state, action, 和 type)。可以用以下的任一方法調用:

parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

注意:關鍵字參數必須跟隨在位置參數的後面

3.5.3 可變參數列表

可變個數的參數。這些參數被包裝進一個list或tuple,在這些可變個數的參數之前,可以有零到多個普通的參數:

def write_multiple_items(file, *args, sep="/"): # Positional ... Arbitrary ... Keyword
    file.write(sep.join(args))

注意*args, **kwargs區別:

  • *args接收一個list或元組(*變量)——多個參數值。
  • **kwargs接收一個字典(**變量)——多個關鍵字參數。
def cal(*args, **kwargs):
    for x in args:
        print(x)
    for k in kwargs:						# for k, v in kwargs.item():
        print('%s = %d' % (k, kwargs[k]))	#     print('%s = %d' % (k, v))

l = [1,2,3,4]
d = {'x':1,'xx':2}
cal(*l, **d) # print: 1
			 # 		  2
			 # 		  3
			 # 		  4
			 # 		  x = 1
			 # 		  xx = 2

3.5.4 Lambda表達式

  • 創建短小的匿名函數。
  • 出於語法限制,它們只能有一個單獨的表達式。
>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

4 數據結構

Python數據結構詳細內容可參閱官方文檔.

4.1 Basic data types

—— integers, floats, booleans, and strings

  • Numbers: Integers, floats, complex
operation result
math.trunc(x) x truncated to Integral
round(x[, n]) x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.
math.floor(x) the greatest Integral <= x
math.ceil(x) the least Integral >= x
>>> x = 3
>>> type(x)
<class 'int'>
>>> print(x + 1)	# Addition
4
>>> print(x * 2)	# Multiplication
6
>>> print(x ** 2)	# Exponentiation
9
>>> print(x / 2)	# Division
1.5
>>> print(x // 2)	# 
1

>>> a = math.trunc(3.1415)
>>> a
3
>>> a = round(3.1415,3)
>>> a
3.142
  • Booleans: and, or, not
>>> a, b, c = 1, 2, 3
>>> if a == 1 and b < c:
...     print('a equals 1, b is smaller than c')
... 
a equals 1, b is smaller than c
  • Strings: 字符串內容見string.

4.2 Sequence Types

基本順序類型有3個——list, tuple, range

  • sequence types通用操作
a = [1, 2, 3]
b = [4, 5, 6]
a + b  		# value: [1, 2, 3, 4, 5, 6]
a.index(2)  # value: 1
>>> a.index(3, 0, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 3 is not in list

注意:序列中item不是copy,而是多次reference.注意以下區別:

lists = [[]] * 3  # lists = [[], [], []]
lists[0].append(3)  # lists = [[3], [3], [3]]

lists = [[] for i in range(3)]  # lists = [[], [], []]
lists[0].append(3)				# lists = [[3], [], []]
lists[1].append(5)				# lists = [[3], [5], []]
lists[0].append(7)				# lists = [[3, 7], [5], []]
  • mutable sequences types操作
    ——list, dict, set

4.2.1 list

class list([iterable])
a = [1, 2, 3, 4]
b = [[1, 2, 3], [4]]
c = [i in range(5)]  # c = [0, 1, 2, 3, 4]
d = list(range(5))   # d = [0, 1, 2, 3, 4]
  • Slicing: access sublists.
nums = list(range(5))     # range is a built-in function that creates a list of integers
print(nums)               # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4])          # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:])           # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2])           # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:])            # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]"
print(nums[:-1])          # Slice indices can be negative; prints "[0, 1, 2, 3]"
nums[2:4] = [8, 9]        # Assign a new sublist to a slice
print(nums)               # Prints "[0, 1, 8, 9, 4]"
  • Loops:
animals = ['cat', 'dog', 'monkey']
for animal in animals:
    print(animal)
# Prints "cat", "dog", "monkey", each on its own line.
  • List comprehensions:
# list comprehension
nums = [0, 1, 2, 3]
squares = [x ** 2 for x in nums]  # squares = [0, 1, 4, 9]

L = [x + y for x in 'ABC' for y in 'XYZ']  # L = ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

除了sequence type通用操作mutable sequence操作,list還有:

sort(*, key=None, reverse=False)

4.2.2 tuple

class tuple([iterable])

注意:tuple和list很相似,除了:

a = (1, 2, 3)
b = 4, a   # b = (4, (1, 2, 3))
c = tuple(i for i in range(3)) # c = (0, 1, 2)
t =(1,) # tupe with only one element

4.2.3 range

class range(stop)
class range(start, stop[, step])
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]

range是immutable sequence type,只能實現sequence type通用操作

4.3 Text Sequence Type — str

class str(object=’’)

class str(object=b'', encoding='utf-8', errors='strict')

str是immutable sequence type,只能實現sequence type通用操作

String文本有許多方式書寫:

  • 單引號:‘allows embedded “double” quotes’
  • 雙引號:“allows embedded ‘single’ quotes”
  • 三引號:’’‘Three single quotes’’’, “”“Three double quotes”""
>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[-1]  # last character
'n'

4.4 Mapping Types — dict

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
pairs = (key, value)

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) # pairs = zip(d.values(), d.keys())
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
  • Dictionary comprehensions:
key = ['one', 'two', 'three','four']
value = [1,2,3,4]

d = {key[i]: value[i] for i in range(len(key)) if i % 2 ==0}
print(d) # print: {'three': 3, 'one': 1}
print(d['one']) # print: 1

避免key不存在的錯誤

  • 通過in判斷key是否存在:
d = {'a':1, 'b':2, 'c':3}
print('a'in d)  # print: True
  • dict.get()方法:key不存在,可以返回None,或者自己指定的value
print(d.get('b')) 		# print: 2
print(d.get('d', -10))  # print: -10

4.5 Set Types — set

class set([iterable])

animals = {'cat', 'dog'}
animals.add('fish')
animals.remove('dog')

a = set([0,1,2])
b = set(range(3))
  • Loops: enumerate
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))
# Prints "#1: fish", "#2: dog", "#3: cat"
  • Set comprehensions:
from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums)  # Prints "{0, 1, 2, 3, 4, 5}"

5 高級特性

可直接作用於for循環的數據類型都是可迭代對象:Iterable,主要有兩種:

  • iterator迭代器,如集合數據類型:listtuplestrdictset
  • generator生成器
  • 凡是可以for循環的,都是Iterable
  • 凡是可以next()的,都是Iterator
    listtuplestrdictIterable,但不是Iterator,可以使用iter()函數將其變爲Iterator
from collections import Iterable
print(isinstance([], Iterable))  # print: True
print(isinstance((), Iterable))  # print: True

from collections import Iterator
print(isinstance([], Iterator))  		# print: False
print(isinstance(iter(()), Iterator))  # print: True
print(isinstance({}, Iterator))		   # print: False
print(isinstance('xxx'.__iter__(), Iterator))  # print: True

5.1 迭代器 — Iterator

  迭代器是包含__iter____next__方法的類。
  創建一個iterator,必須實現一個有__iter__()__next__()方法的類,類要能夠跟蹤內部狀態並且在沒有元素返回的時候引發StopIteration異常.

class Fibs:
	def __init__(self, threshold=20):
		self.a = 0
		self.b = 1
		self.maxnum = threshold
	
	def __iter__(self):
		return self
	
	def __next__(self):
		self.a, self.b = self.b, self.a + self.b
		if self.a > self.threshold:
			raise StopItearation
		else:
			return self.a

使用該迭代器:

fib = Fibs()
for each in fib:
	print each	# 依次打印 1, 1, 2, 3, 5, 8, 13

5.2 生成器 — generator

  生成器是特殊類型的迭代器
  Python generator可以方便地創建iterator,自動實現__iter____next__方法。
——邊循環邊計算、按需生成

  • 方法一:列表生成器的[]改爲()產生generator
g = (x ** 2 for x in range(3))  # g: <generator object <genexpr> at 0x7fc5cf37a728>
print(next(g))  # print: 0
print(next(g))  # print: 1
print(next(g))  # print: 4
print(next(g))  # Exception: StopIteration

使用for循環可以自動捕獲StopIteration異常:

for x in g:
    print(x)
  • 方法二:generator函數
  • generator函數包含一個以上的yield聲明
  • generator函數被調用的時候,會返回一個iterator對象,但是函數並不會立即開始執行
  • __iter__()__next__()方法被自動實現,所以可以使用next()函數對返回的此iterator對象進行迭代。
  • 函數執行過程:每調用一次next(),生成器函數就運行到一個yield處,並保存狀態且返回yield後的數據,下次調用next,生成器函數從上次yield語句後開始運行,直到沒有yield語句後,函數執行到末尾,再調用next就會觸發StopIteration異常。
def my_gen():
    n = 10
    print('1st')
    yield n

    n += 1
    print('2nd')
    yield n

    n+=1
    print('3rd')
    yield n

g = my_gen()
print(g.__next__())  # print: 1st
					 #        10
g.__next__()		 # print: 2nd
next(g)				 # print: 3rd

6 模塊 Module

Python中一個.py文件就稱之爲模塊(Module).
如:abc.py文件就是一個名字叫abc的模塊。
如果模塊名字衝突,可以通過包來組織模塊,避免衝突。

如下文件目錄:

mycompany
├─ __init__.py
├─ abc.py
└─ xyz.py

模塊名變爲:mycompany.abcmycompany.xyz

注意:每個package包目錄下都有一個__init__.py的文件,以表明這是一個Python包。

  • __init__.py可以是空文件,也可以有Python代碼。
  • 包含有多個模塊。
  • 從包內導入模塊:import mycompany.abc as abc

6.1 使用模塊

Python內置了很多有用的模塊,可以立即使用(import ... as ...),自己編寫的模塊也能立即使用。
file: one.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ywq'

def func():
    print('func() in one.py')

print('top-level in one.py')

if __name__ == '__main__':
    print('one.py is runing directly')
else:
    print('one.py is imported into another module')

file two.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ywq'

import one # start executing one.py

print('top-level in two.py')
one.func()

if __name__ == '__main__':
    print('two.py is runing directly')
else:
    print('two.py is imported into another module')

運行python3 one.py,輸出:

top-level in one.py
one.py is runing directly

運行python3 two.py,輸出:

top-level in one.py
one.py is imported into another module
top-level in two.py
func() in one.py
two.py is runing directly

說明if __name__ == '__main':只有在直接運行模塊時爲True,被其他模塊導入時爲False.

6.2 安裝第三方模塊

  一般來說,第三方庫都會在Python官方網站註冊,要安裝一個第三方庫,必須先知道該庫的名稱,可以在官網或者pypi上搜索,再使用安裝命令:

python3 -m pip install xxx
# 或者
pip3 install xxx
  • 模塊搜索路徑
    模塊搜索路徑在sys模塊的path變量中。
    使用import導入模塊時,系統會從搜索路徑中查找模塊。
>>> import sys
>>> sys.path
['', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/ywq/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages']

注意:該結果中'/home/ywq/.local/lib/python3.5/site-packages'路徑爲pip3方式安裝第三方庫的存儲位置。

添加搜索路徑的方法:
方法一:直接修改sys.path值,添加要搜索的目錄:

>>> import sys
>>> sys.path.append('/Users/michael/my_py_scripts')

在運行時修改,運行結束後失效。

方法二:設置環境變量PYTHONPATH
/etc/profile.d下建立python.sh文件,並在文件最後加入代碼,如:

export PYTHONPATH=/home/ywq/Documents/:$PYTHONPATH

終端輸入$ source /etc/profile使配置生效.

注意:python3 -m-m表示以模塊方式執行python文件(命令),主要是把輸入命令的目錄(也就是當前路徑),放到了sys.path屬性中.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章