1. 程式人生 > 實用技巧 >python3參考祕籍-附PDF下載

python3參考祕籍-附PDF下載

目錄

簡介

Python作為一個開源的優秀語言,隨著它在資料分析和機器學習方面的優勢,已經得到越來越多人的喜愛。據說小學生都要開始學Python了。

Python的優秀之處在於可以安裝很多非常強大的lib庫,從而進行非常強大的科學計算。

講真,這麼優秀的語言,有沒有什麼辦法可以快速的進行學習呢?

有的,本文就是python3的基礎祕籍,看了這本祕籍python3的核心思想就掌握了,文末還有PDF下載連結哦,歡迎大家下載。

Python的主要資料型別

python中所有的值都可以被看做是一個物件Object。每一個物件都有一個型別。

下面是三種最最常用的型別:

  • Integers (int)

整數型別,比如: -2, -1, 0, 1, 2, 3, 4, 5

  • Floating-point numbers (float)

浮點型別,比如:-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25

  • Strings

字串型別,比如:“www.flydean.com”

注意,字串是不可變的,如果我們使用replace() 或者 join() 方法,則會建立新的字串。

除此之外,還有三種類型,分別是列表,字典和元組。

  • 列表

列表用方括號表示: a_list = [2, 3, 7, None]

  • 元組

元組用圓括號表示: tup=(1,2,3) 或者直接用逗號表示:tup=1,2,3

Python中的String操作

python中String有三種建立方式,分別可以用單引號,雙引號和三引號來表示。

基本操作

my_string = “Let’s Learn Python!”
another_string = ‘It may seem difficult first, but you can do it!’
a_long_string = ‘’‘Yes, you can even master multi-line strings
 that cover more than one line
 with some practice’’’

也可以使用print來輸出:

print(“Let’s print out a string!”)

String連線

String可以使用加號進行連線。

string_one = “I’m reading “
string_two = “a new great book!” 
string_three = string_one + string_two

注意,加號連線不能連線兩種不同的型別,比如String + integer,如果你這樣做的話,會報下面的錯誤:

TypeError: Can’t convert ‘int’ object to str implicitly

String複製

String可以使用 * 來進行復制操作:

‘Alice’ * 5 ‘AliceAliceAliceAliceAlice’

或者直接使用print:

print(“Alice” * 5)

Math操作

我們看下python中的數學操作符:

操作符 含義 舉例
** 指數操作 2 * 3 = 8*
% 餘數 22 % 8 = 6
// 整數除法 22 // 8 = 2
/ 除法 22 / 8 = 2.75
***** 乘法 3*3= 9
- 減法 5-2= 3
+ 加法 2+2= 4

內建函式

我們前面已經學過了python中內建的函式print(),接下來我們再看其他的幾個常用的內建函式:

  • Input() Function

input用來接收使用者輸入,所有的輸入都是以string形式進行儲存:

name = input(“Hi! What’s your name? “) 
print(“Nice to meet you “ + name + “!”)
age = input(“How old are you “)
print(“So, you are already “ + str(age) + “ years old, “ + name + “!”)

執行結果如下:

Hi! What’s your name? “Jim”
Nice to meet you, Jim!
How old are you? 25
So, you are already 25 years old, Jim!
  • len() Function

len()用來表示字串,列表,元組和字典的長度。

舉個例子:

# testing len()
str1 = “Hope you are enjoying our tutorial!” 
print(“The length of the string is :”, len(str1))

輸出:

The length of the string is: 35
  • filter()

filter從可遍歷的物件,比如列表,元組和字典中過濾對應的元素:

ages = [5, 12, 17, 18, 24, 32]
def myFunc(x):
  if x < 18:
    return False
  else:
return True
adults = filter(myFunc, ages)
for x in adults:
  print(x)

函式Function

python中,函式可以看做是用來執行特定功能的一段程式碼。

我們使用def來定義函式:

def add_numbers(x, y, z): 
  a= x + y
	b= x + z
	c= y + z 
	print(a, b, c)
  
add_numbers(1, 2, 3)

注意,函式的內容要以空格或者tab來進行分隔。

傳遞引數

函式可以傳遞引數,並可以通過通過命名引數賦值來傳遞引數:

# Define function with parameters
def product_info(productname, dollars):
    print("productname: " + productname)
    print("Price " + str(dollars))


# Call function with parameters assigned as above
product_info("White T-shirt", 15)

# Call function with keyword arguments
product_info(productname="jeans", dollars=45)

列表

列表用來表示有順序的資料集合。和String不同的是,List是可變的。

看一個list的例子:

my_list = [1, 2, 3]
my_list2 = [“a”, “b”, “c”] 
my_list3 = [“4”, d, “book”, 5]

除此之外,還可以使用list() 來對元組進行轉換:

 alpha_list = list((“1”, “2”, “3”)) 
 print(alpha_list)

新增元素

我們使用append() 來新增元素:

beta_list = [“apple”, “banana”, “orange”] 
beta_list.append(“grape”) 
print(beta_list)

或者使用insert() 來在特定的index新增元素:

beta_list = [“apple”, “banana”, “orange”] 
beta_list.insert(“2 grape”) 
print(beta_list)

從list中刪除元素

我們使用remove() 來刪除元素

beta_list = [“apple”, “banana”, “orange”] 
beta_list.remove(“apple”) 
print(beta_list)

或者使用pop() 來刪除最後的元素:

beta_list = [“apple”, “banana”, “orange”] 
beta_list.pop()
print(beta_list)

或者使用del 來刪除具體的元素:

beta_list = [“apple”, “banana”, “orange”] 
del beta_list [1]
print(beta_list)

合併list

我們可以使用+來合併兩個list:

my_list = [1, 2, 3]
my_list2 = [“a”, “b”, “c”] 
combo_list = my_list + my_list2 
combo_list
[1, 2, 3, ‘a’, ‘b’, ‘c’]

建立巢狀的list

我們還可以在list中建立list:

my_nested_list = [my_list, my_list2] 
my_nested_list
[[1, 2, 3], [‘a’, ‘b’, ‘c’]]

list排序

我們使用sort()來進行list排序:

alpha_list = [34, 23, 67, 100, 88, 2] 
alpha_list.sort()
alpha_list
[2, 23, 34, 67, 88, 100]

list切片

我們使用[x:y]來進行list切片:

 alpha_list[0:4]
[2, 23, 34, 67]

修改list的值

我們可以通過index來改變list的值:

beta_list = [“apple”, “banana”, “orange”] 
beta_list[1] = “pear”
print(beta_list)

輸出:

[‘apple’, ‘pear’, ‘cherry’]

list遍歷

我們使用for loop 來進行list的遍歷:

for x in range(1,4): 
  beta_list += [‘fruit’] 
  print(beta_list)

list拷貝

可以使用copy() 來進行list的拷貝:

beta_list = [“apple”, “banana”, “orange”] 
beta_list = beta_list.copy() 
print(beta_list)

或者使用list()來拷貝:

beta_list = [“apple”, “banana”, “orange”] 
beta_list = list (beta_list) 
print(beta_list)

list高階操作

list還可以進行一些高階操作:

list_variable = [x for x in iterable]

 number_list = [x ** 2 for x in range(10) if x % 2 == 0] 
 print(number_list)

元組

元組的英文名叫Tuples,和list不同的是,元組是不能被修改的。並且元組的速度會比list要快。

看下怎麼建立元組:

my_tuple = (1, 2, 3, 4, 5) 
my_tuple[0:3]
(1, 2, 3)

元組切片

 numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) 
 print(numbers[1:11:2])

輸出:

(1,3,5,7,9)

元組轉為list

可以使用list和tuple進行相互轉換:

x = (“apple”, “orange”, “pear”) 
y = list(x)
y[1] = “grape”
x = tuple(y)
print(x)

字典

字典是一個key-value的集合。

在python中key可以是String,Boolean或者integer型別:

 Customer 1= {‘username’: ‘john-sea’, ‘online’: false, ‘friends’:100}

建立字典

下面是兩種建立空字典的方式:

new_dict = {}
other_dict= dict()

或者像下面這樣來初始賦值:

new_dict = { 
  “brand”: “Honda”, 
  “model”: “Civic”, 
  “year”: 1995
}
print(new_dict)

訪問字典的元素

我們這樣訪問字典:

x = new_dict[“brand”]

或者使用dict.keys()dict.values()dict.items()來獲取要訪問的元素。

修改字典的元素

我們可以這樣修改字典的元素:

#Change the “year” to 2020:
new_dict= { 
  “brand”: “Honda”, 
  “model”: “Civic”, 
  “year”: 1995
}
new_dict[“year”] = 2020

遍歷字典

看下怎麼遍歷字典:

#print all key names in the dictionary
for x in new_dict:
  print(x)
#print all values in the dictionary
for x in new_dict:
  print(new_dict[x])
#loop through both keys and values
for x, y in my_dict.items(): print(x, y)

if語句

和其他的語言一樣,python也支援基本的邏輯判斷語句:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

看下在python中if語句是怎麼使用的:

if 5 > 1:
	print(“That’s True!”)

if語句還可以巢狀:

x = 35
	if x > 20:
		print(“Above twenty,”) 
    if x > 30:
			print(“and also above 30!”)

elif

a = 45
b = 45
if b > a:
	print(“b is greater than a”) 
elif a == b:
	print(“a and b are equal”)

if else:

if age < 4: 
ticket_price = 0
elif age < 18: 
ticket_price = 10
else: ticket_price = 15

if not:

new_list = [1, 2, 3, 4] 
x = 10
if x not in new_list:
	print(“’x’ isn’t on the list, so this is True!”)

Pass:

a = 33 
b = 200
if b > a: 
  pass

Python迴圈

python支援兩種型別的迴圈,for和while

for迴圈

 for x in “apple”: 
    print(x)

for可以遍歷list, tuple,dictionary,string等等。

while迴圈

#print as long as x is less than 8
i =1 
while i< 8:
	print(x) 
  i += 1

break loop

i =1
while i < 8:
	print(i) 
  if i == 4:
		break
	i += 1

Class

Python作為一個面向物件的程式語言,幾乎所有的元素都可以看做是一個物件。物件可以看做是Class的例項。

接下來我們來看一下class的基本操作。

建立class

 class TestClass: 
    z =5

上面的例子我們定義了一個class,並且指定了它的一個屬性z。

建立Object

 p1 = TestClass() 
 print(p1.x)

還可以給class分配不同的屬性和方法:

class car(object):
  “””docstring”””
	def __init__(self, color, doors, tires):
    “””Constructor”””
		self.color = color
    self.doors = doors
    self.tires = tires
    
	def brake(self):
    “””
		Stop the car
		“””
		return “Braking”
  
	def drive(self): 
    “””
		Drive the car
		“””
		return “I’m driving!”

建立子類

每一個class都可以子類化

class Car(Vehicle):
  “””
	The Car class 
  “””
  
def brake(self):
  “””
	Override brake method
	“””
	return “The car class is breaking slowly!”

if __name__ == “__main__”:
	car = Car(“yellow”, 2, 4, “car”)
  car.brake()
	‘The car class is breaking slowly!’
  car.drive()
	“I’m driving a yellow car!”

異常

python有內建的異常處理機制,用來處理程式中的異常資訊。

內建異常型別

  • AttributeError — 屬性引用和賦值異常
  • IOError — IO異常
  • ImportError — import異常
  • IndexError — index超出範圍
  • KeyError — 字典中的key不存在
  • KeyboardInterrupt — Control-C 或者 Delete時,報的異常
  • NameError — 找不到 local 或者 global 的name
  • OSError — 系統相關的錯誤
  • SyntaxError — 直譯器異常
  • TypeError — 型別操作錯誤
  • ValueError — 內建操作引數型別正確,但是value不對。
  • ZeroDivisionError — 除0錯誤

異常處理

使用try,catch來處理異常:

my_dict = {“a”:1, “b”:2, “c”:3}
try:
		value = my_dict[“d”]
except KeyError:
		print(“That key does not exist!”)

處理多個異常:

my_dict = {“a”:1, “b”:2, “c”:3}
try:
	value = my_dict[“d”]
except IndexError:
	print(“This index does not exist!”)
except KeyError:
	print(“This key is not in the dictionary!”)
except:
	print(“Some other problem happened!”)

try/except else:

my_dict = {“a”:1, “b”:2, “c”:3}
try:
	value = my_dict[“a”]
except KeyError:
	print(“A KeyError occurred!”)
else:
	print(“No error occurred!”)

本文已收錄於 http://www.flydean.com/python3-cheatsheet/

最通俗的解讀,最深刻的乾貨,最簡潔的教程,眾多你不知道的小技巧等你來發現!

歡迎關注我的公眾號:「程式那些事」,懂技術,更懂你!