簡介
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!”)
- 最後附上Python3秘籍的PDF版本: python3-cheatsheet.pdf
本文已收錄于 http://www.flydean.com/python3-cheatsheet/最通俗的解讀,最深刻的幹貨,最簡潔的教程,衆多你不知道的小技巧等你來發現!
歡迎關注我的公衆号:「程式那些事」,懂技術,更懂你!