文章目錄
- 簡介
- Python的主要資料型別
- Python中的String操作
- 基本操作
- String連接
- String復制
- Math操作
- 內置函式
- 函式**Function**
- 傳遞引數
- 串列
- 添加元素
- 從list中洗掉元素
- 合并list
- 創建嵌套的list
- list排序
- list切片
- 修改list的值
- list遍歷
- list拷貝
- list高級操作
- 元組
- 元組切片
- 元組轉為list
- 字典
- 創建字典
- 訪問字典的元素
- 修改字典的元素
- 遍歷字典
- if陳述句
- Python回圈
- for回圈
- while回圈
- break loop
- Class
- 創建class
- 創建Object
- 創建子類
- 例外
- 內置例外型別
- 例外處理
簡介
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/
最通俗的解讀,最深刻的干貨,最簡潔的教程,眾多你不知道的小技巧等你來發現!
歡迎關注我的公眾號:「程式那些事」,懂技術,更懂你!
CSDN認證博客專家
Java專家
全堆疊作業者
區塊鏈達人
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/240535.html
標籤:python
下一篇:Python入門
