主用python做專案有一段時間,這次簡單總結學習下,為后面的專案撰寫,進行一次基礎知識的查缺補漏、
1、變數名和資料型別
"""
變數名,只能由" 數字、大小寫字母、_ " 組成,且不能以數字開頭
"""
# 整數 int
# hashable,不可變物件
a = 5
# 浮點數 float
# hashable,不可變物件
a1 = 3.14
# 字串 string
# hashable,不可變物件
a_1 = "哈哈哈"
str_num = '5'
_str_float = """3.14"""
_ = '''hello world''' # 常常用于接收我們不需要使用的值
# 串列 list
# 元素可修改,元素有順序
# 串列是unhashable, 可變物件
tmp_list = [1, 3.14, "haha", [7, "qq"]]
# 元組 tuple
# 元素不可修改,元素有順序
# 元組是hashable,不可變物件
tmp_tuple = (1, 3.14, "haha", [7, "qq"])
# 集合 set
# 元素不重復,即使重復,也會自動去重,元素沒有順序
# 元素必須是hashable,不可變物件
# 集合是unhashable, 可變物件
tmp_set = {1, 1, 3.14, "haha"}
# 字典 dict 鍵值對形式--key:value,key不能重復
# key必須為hashable,不可變物件
# 字典是unhashable,可變物件
tmp_dict = {1: "xy", "a": 123, (1, "a"): [1, "abc", 3]}
# 布林值 bool
# 布林值是hashable,不可變物件
x = True
y = False
# None 不是0,不是空字串"",不是False,啥也不是
# None是hashable, 不可變物件
t = None
# 常量 變數名用大寫字母
# 約定俗成,并不是不可變
PI = 3.1415926
INT_LIST = [1, 2, 3, 4, 5]
2、注釋&格式化輸出
# 注釋:對代碼的說明性文字,不參與代碼運行、運算
# 單行注釋
"""
多行注釋
多行注釋
多行注釋
"""
'''
多行注釋
多行注釋
多行注釋
'''
# 格式化輸入
name = "alex"
age = 100
# 占位符(不推薦)
res = "姓名: %s,年齡: %d" % (name, age) # 字串就是%s 整數就是%d 浮點數%f
print("占位符輸出: %s" % res)
# format(推薦)
res = "姓名:{},年齡:{}".format(name, age)
res = "姓名:{name},年齡:{age}".format(age=age, name=name)
print("format函式輸出:{}".format(res))
# f前綴(python3.6以上)
res = f"姓名:{name},年齡:{age}"
print(f"f前綴輸出:{res}")
3、代碼執行順序
先呼叫會報錯,放在后面即可運行,

"""
從上往下執行
"""
a = 3
def plus(x, y):
return x + y
b = plus(a, 5)
print(b)

4、算數運算子&整浮互相轉化&精度問題
"""
算術運算子: +、 -、 *、 /、 //、 **、%
"""
# 加
res = 2 + 3
print(f"2 + 3 = {res}")
# 減
res = 2 - 3
print(f"2 - 3 = {res}")
# 乘
res = 2 * 3
print(f"2 * 3 = {res}")
# 除
res = 2 / 3
print(f"2 / 3 = {res}")
# 整除
res = 5 // 2
print(f"5 // 2 = {res}")
# 取余
res = 5 % 2
print(f"5 % 2 = {res}")
# 次冪
res = 2 ** 3
print(f"2 ** 3 = {res}") # 2的三次方
"""
浮點數和整數的互相轉換
以及常用函式abs
"""
# 整數轉浮點數
a = 5
print("a = 5, a的型別為:{}".format(type(a)))
a = float(a)
print("float(a) = {}, a的型別為:{}".format(a, type(a)))
# 浮點數轉整數,直接取整數位,沒有四舍五入
b = 3.55
print("b = 3.55, b的型別為:{}".format(type(b)))
b = int(b)
print("int(b) = {}, b的型別為:{}".format(b, type(b)))
# abs 取絕對值
c = -3.14
print("c = -3.14, c的型別為:{}".format(type(c)))
c = abs(c)
print("abs(c) = {}, c的型別為:{}".format(c, type(c)))
# round,精度低,不推薦
b = 3.55
b = round(b, 1)
print("round(b) = {},b的型別為:{}".format(b, type(b))) # 3.5不是3.6
# 標準庫decimal
from decimal import Decimal
b = 3.55
b = str(b)
b = Decimal(b).quantize(Decimal("0.1"),rounding="ROUND_HALF_UP") # 四舍五入 Decimal保留小數的位數
print("round(b) = {},b的型別為:{}".format(b, type(b)))
5、賦值運算子
"""
賦值運算子:
=, +=, -=, *=, /=, //=, %=, **=
"""
a = 2
a = a + 2 # a = 4
a += 2 # a = 6
a = a - 2 # a = 4
a -= 2 # a = 2
a = a * 2 # a = 4
a *= 2 # a = 8
6.1、編碼
"""
在計算機中存盤的是二進制數 10011011
在計算機最小存盤單位,1位二進制數,即1個Bit(位元)
1 Byte(位元組) = 8 Bits
1 KB = 1024 Bytes 2**10 = 1024
1 MB = 1024 KB
編碼問題:
1、ASCII編碼,只有大小寫字母、數字、特色符號,
用1個Byte表示一個字符
例如:字母A 01000001
2、GB2312,Euc-kr,Shift_JIS ...
各國有各國的標準,必然會沖突,即亂碼
3、Unicode編碼(萬國碼),所有語言統一使用這一套編碼
通常用2個Byte表示一個字符(生僻字符要4個Byte)
依然存在問題:
例如用戶只用英文的話,采用這種編碼,
占用的存盤空間是ASCII編碼的2倍,
例如:字母A 00000000 01000001
4、UTF-8編碼
把Unicode字符集編碼成1-6個Byte
(1)大小寫英文字母、數字、特殊符號
維持ASCII編碼,1個Byte
例如,字母A的ASCII碼和UTF-8碼是一樣的
01000001
(2)中文通常是 3個Byte
(3)生僻的字符 4-6個Byte
5、Python3.X 原始碼.py檔案默認使用UTF-8
Python3.X 默認使用ASCII,所以需要指明
# -*- coding:UTF-8 -*-
6、計算機記憶體中,使用的是Unicode編碼
需要存盤或傳輸時,會吧記憶體中的Unicode轉為UTF-8
"""
6.2、字串常用方法
"""
去除首尾指定字符,默認去除空格,回傳值均為字串
strip() # 左右都去除
lstrip() # 只去除左邊
rstrip() # 只去除右邊
"""
tmp = "----舉個--栗子---"
tmp_lstrip = tmp.lstrip("-")
tmp_rstrip = tmp.rstrip("-")
tmp_strip = tmp.strip("-")
print("tmp_lstrip:{}".format(tmp_lstrip))
print("tmp_rstrip:{}".format(tmp_rstrip))
print("tmp_strip:{}".format(tmp_strip))
"""
startswith() 判斷字串是否以指定的字串開頭
endswith() 判斷字串是否以指定的字串結尾
回傳值均為布林值,即True或False
"""
tmp = "這次繼續舉個栗子"
if tmp.startswith("這次"):
print("tmp是以'這次'開頭的")
if tmp.endswith("子"):
print("tmp是以'子'結尾的")
"""
分割字串
split(sep, maxsplit):
1、sep:指定分割符,默認為空格
2、maxsplit:分割次數,默認為-1即全部分割
3、回傳值為一個串列list
"""
tmp = "Python,C,C++,Java,Vue"
res = tmp.split(",")
res_2 = tmp.split(",", 2)
print("res:{}".format(res))
print("res_2:{}".format(res_2))
"""
lower() 全轉為小寫
upper() 全轉為大寫
"""
tmp = "What's up! Man!"
tmp_l = tmp.lower()
tmp_u = tmp.upper()
print("大寫:{}".format(tmp_u))
print("小寫:{}".format(tmp_l))
"""
is系列方法,最常用的三個:
isalpha() 判斷字串是否僅含有字母
isdigit() 判斷字串是否僅含有數字
isalnum() 判斷字串是否僅含字母或數字
均回傳布林值,即True或False
"""
tmp_1 = "23"
tmp_2 = "python"
tmp_3 = "python666"
if tmp_1.isdigit():
print("tmp_1中僅含數字")
if tmp_2.isalpha():
print("tmp_2中僅含字母")
if tmp_3.isalnum():
print("tmp_3中僅含字母或數字")
"""
子字串替換
replace(old, new, count)
1、old:被替換的子字串
2、new:新的子字串
3、count:替換次數,默認為-1全部替換
"""
tmp = "Python66666"
# 全部替換
tmp_1 = tmp.replace("6", "9")
# 從左往右,替換指定次數
tmp_2 = tmp.replace("6", "1", 4)
# 找不到指定的子字串,則不替換
tmp_3 = tmp.replace("java", "go")
print(tmp_1)
print(tmp_2)
print(tmp_3)
"""
獲取子字符的索引
1、index(sub,start,end) 從左往右
1)sub,子字符
2)start,查找的起始位置
3)end,查找的終止位置-1
2、rindex() 從右往左
3、只找一個,且若sub存在,則會報錯
"""
# 012345678
tmp = "Python666"
# 正向查找
index_1 = tmp.index("6", 5, 7) # 實際是在第5個索引和第6個索引查找
# 反向查找
index_2 = tmp.rindex("6")
print("index_1:{}".format(index_1))
print("index_2:{}".format(index_2))
6.3、字串轉義
"""
字串轉義:
\n 換行符,將游標位置移到下一行開頭,
\r 回車符,將游標位置移到本行開頭,
\t 水平制表符,即Tab鍵
\a 蜂鳴器響鈴,現在的電腦一般都沒有蜂鳴器了
\b 退格(Backspace),將游標位置移到前一列,
\\ 反斜杠
\' 單引號
\" 雙引號
"""
a = "這是換行,\n 這是\r回車符,這是\t制表符," \
"這里是退格\b\n" \
"這是反斜杠\\, 這是單引號\', 這是雙引號\""
print(a)
7、比較運算子&if...else
"""
比較運算子: ==, !=, >, >=, <, <=
運算結果都是布林值,即True或者False
"""
a = 1
b = 1
c = 2
# 單個if
if a == b:
res = a - b
print(f"a等于b,a-b={res}")
# if...else...
if a != b:
print("a不等于b")
else:
print("a等于b")
# if...elif...elif..............else...
if a > b:
print("a大于b")
elif a == b:
print("a等于b")
elif a < b:
print("c大于a")
else:
print()
# 嵌套
if a >= b:
print("a大于等于b")
if a == b:
print("a等于b")
else:
print("a不等于b")
8、身份運算子
"""
身份運算子:is,is not(嘗用于判斷是否為None)# 兩個變數記憶體地址是否相同
運算結果為布林值,即True或False
x is y 等效于 id(x) == id(y)
x is not y 等效于 id(x) != id(y)
"""
# 小整數池: -5~256
a = -5
b = -5
print("均為-5,a is b結果為{}".format(a is b))
print("id(a)={},id(b)={}\n".format(id(a), id(b)))
# 在pycharm運行會是true:pc會先保存257的記憶體地址,發現b也是257 b指向a的記憶體地址
a = 257
b = 257
print("均為257,a is b結果為{}".format(a is b))
print("id(a)={},id(b)={}\n".format(id(a), id(b)))
# 字串池: 長度不超過20,且沒有空格,記憶體地址相同
a = "test"
b = "test"
print("均為\"test\",a is b結果為{}".format(a is b))
print("id(a)={},id(b)={}\n".format(id(a), id(b)))
a = "te st"
b = "te st"
print("均為\"te st\",a is b結果為{}".format(a is b))
print("id(a)={},id(b)={}\n".format(id(a), id(b)))
# 代碼在終端運行則會不一樣
? 這種情況可能是因為Python的整數快取機制導致的,具體表現為在某些情況下,Python會快取一些整數物件以提高性能,這些物件的參考會被多個變數共享,根據官方檔案,Python 3.7及更高版本中,整數物件的快取機制默認會快取從-5到256之間的整數物件,
在Python中,我們應該使用==運算子來比較兩個物件的值是否相等,而不是使用is運算子來比較它們是否是同一個物件,
9、成員運算子
"""
成員運算子:in not in
運算結果為布林值,即True或者False
"""
tmp_str = "Hello, World"
tmp_list = [1, 2, 3, "a", "b"]
tmp_tuple = (1, 2, 3, "a", "b")
tmp_set = {1, 2, 3, "a", "b"}
tmp_dict = {"a": 1, "b": 2}
if "lo" in tmp_str:
print(f"lo在字串{tmp_str}中")
if 4 not in tmp_list:
print(f"4不在串列{tmp_list}中")
# 字典是判斷存在"a"這個key
if "a" in tmp_dict:
print(f"a在字典{tmp_dict}中")
if 1 in tmp_dict:
print(f"1在字典{tmp_dict}中")
10、邏輯運算子
"""
邏輯運算子:and(與), or(或), not(非)
"""
a = 1
b = 2
c = 3
# x and y,要求x和y都為True, 運算結果才為True,
# 否則為False
if a < c and b < c:
print("a小于c,且b小于c")
else:
print("a不小于c或者b不小于c")
# x or y,只要x和y中有一個為True,運算結果就為True,
# 否則為False
if b > a or b > c:
print("b大于a或者b大于c")
else:
print("b不大于a且b不大于c")
# not x,取相反的值
if not (a < b): # 小括號運算優先級最高 不然就把a取反了
print("a不小于b")
else:
print("a小于b")
11、串列&元組
# 空串列
a = []
b = list()
c = [1, 2, 3]
# 空元組
d = ()
e = tuple()
# 定義只有一個元素的元組,一定要加一個逗號,
f = ("a",)
g = ("a") # 不然括號只能算是一個優先級的運算子,只會是一個字串
print(f"f的資料型別為{type(f)}")
print(f"g的資料型別為{type(g)}")
"""
追加串列元素
list.append(item)
1、item,為任意元素
2、回傳值為None
"""
tmp = ["a", 3, "c"]
tmp.append(["b", 1])
print(f"tmp.append([\"b\",1])追加到原始串列:{tmp}")
"""
將元素插入串列
list.insert(index,item)
1、index,插入位置的索引
2、item,要插入的元素
3、回傳值為None
當index大于串列最大正向索引時,插入尾端
當index小于串列最小反向索引時,插入首端
"""
# 0 1 2
# -3 -2 -1
tmp = ["a", "c", "d"]
tmp.insert(1, "b")
print(tmp)
"""
串列的合并
list.extend(iterable)
1、iterable,可迭代物件
字串、串列、元組、集合、字典,,,
2、回傳值為None
"""
tmp = [1, 2, 3]
tmp_new = [4, 5, 6, 7]
tmp.extend(tmp_new)
print(f"tmp.extend(tmp_new)改變原始串列:{tmp}")
"""
洗掉指定索引的元素
list.pop(index)
1、index,要洗掉元素的索引
2、不傳index,默認洗掉最后一個
3、有回傳值,回傳被洗掉的元素
4、若串列為空串列,或者,index超出串列范圍都會報錯
"""
tmp = ["Python", "Java", "Go", "C"]
a = tmp.pop()
print(f"先刪掉了{a},{tmp}")
b = tmp.pop(1)
print(f"再刪掉了{b},{tmp}")
"""
洗掉指定元素(從左往右找,只洗掉找到的第一個)
list.remove(item)
1、item,要洗掉的元素
2、回傳值為None
3、若指定的洗掉元素不存在,則報錯
"""
tmp = ["Python", "Java", "Go", "C"]
tmp.remove("Java")
print(f"tmp.remove(\"Java\")改變原始串列:{tmp}")
"""
清空&清除部分
1、list.clear()
2、del list[index]
3、del list[start:end]
回傳值為None,均作用于原始串列
"""
tmp1 = ["Python", "Java", "Go"]
tmp1.clear()
print(f"tmp1.clear()結果:{tmp1}")
tmp2 = ["Python", "Java", "Go", "C"]
del tmp2[-1]
print(f"tmp2[-1]結果:{tmp2}")
del tmp2[1:] # 索引切片1到末尾全刪
print(f"tmp2[1:]結果:{tmp2}")
del tmp2[:] # 整個串列全都清空
print(f"tmp2[:]結果:{tmp2}")
"""
串列翻轉
1、list.reverse()
改變原串列,回傳值為None
2、切片,list[::-1]
不改變原串列,會生成新的串列
"""
tmp = [1, 2, 3, 4, 5]
tmp.reverse()
print(f"tmp.reverse()翻轉原始串列:{tmp}")
"""
串列排序
1、list.sort() 回傳值為None,改變原始串列
2、 sorted(list) 有回傳值,生成新串列,原始不變
"""
tmp = [4, 1, 3, 2, 5]
tmp.sort()
print(f"tmp.sort()改變原始串列:{tmp}")
tmp = [4, 1, 3, 2, 5]
tmp.sort(reverse=True) # 降序
print(f"tmp.sort(reverse = True)降序:{tmp}")
tmp = [4, 1, 3, 2, 5]
res = sorted(tmp) # 升序
print(f"sorted(tmp)新生成串列:{res}")
tmp = [4, 1, 3, 2, 5]
res = sorted(tmp, reverse=True)
print(f"sorted(tmp,reverse = True)降序:{res}")
"""
統計指定元素在串列中出現的次數
list.count(item)
1、item:要統計的元素
2、回傳值為整數
"""
tmp = ["a", 2, 3, 2, "2", "2", "2"]
count_num_2 = tmp.count(2)
count_str_2 = tmp.count("2")
print(f"數字2出現了{count_num_2}次")
print(f"字串\"2\"出現了{count_str_2}次")
12、集合常用方法
a = {} # 這是空字典
b = set() # 這才是空集合
print(f"a = {{}}的資料型別為{type(a)}")
print(f"b = set()的資料型別為{type(b)}")
c = {1, 2, 2, 2, 3, 4, 5}
"""
集合,添加元素
1、set.add(item) 添加單個元素
2、set.update(item) 添加多個元素
回傳值均為None,改變原始集合
"""
tmp = {"a", "b", "c"}
tmp.add("c")
tmp.add("1")
tmp.update(["1", "c"]) # 串列、元組、集合均可
print(tmp)
"""
移除元素
1、set.remove(item) 回傳值為None,改變原始集合
item不存在,會報錯
2、set.discard(item) 回傳值為None,改變原始集合
item不存在,不會報錯
3、set.pop() 改變原始集合
隨機洗掉一個元素,并回傳被洗掉的元素
"""
tmp = {"a", "b", "c", "d", "e"}
tmp.remove("c")
tmp.discard("f")
x = tmp.pop()
print(f"tmp.pop()隨機移除了{x}")
print(f"tmp={tmp}")
"""
求合集(集合的合并)
1、set_a.union(set_b,set_c,...)
2、set_a | set_b | set_c | ...
(豎桿,不是斜杠)
"""
set1 = {"Python", "Go"}
set2 = {"Python", "Rust"}
new_set1 = set1.union(set2)
print(f"set1 set2合集為{new_set1}")
"""
求差集
1、set_a.difference(set_b,set_c,...)
2、set_a - set_b - set_c - ...
均不改變原始集合,回傳值是新的集合
"""
set1 = {"Python", "Go"}
set2 = {"Python", "Rust"}
new_set1 = set1.difference(set2)
# new_set1 = set1 - set2
new_set2 = set2.difference(set1)
# new_set2 = set2 - set1
print(f"set1 - set2 = {new_set1}")
print(f"set2 - set1 = {new_set2}")
"""
求交集(找共同的元素)
1、set_a.intersection(set_b,set_c,...)
2、set_a & set_b & set_c & ...
均不改變原始集合,回傳值是新的集合
"""
set1 = {"Python", "Go"}
set2 = {"Python", "Rust"}
new_set1 = set1.intersection(set2)
print(f"set1,set2交集為{new_set1}")
"""
求不重合集
set_a.symmetric_difference(set_b,set_c,...)
不改變原始集合,回傳值是新的集合
"""
set1 = {"Python","Go"}
set2 = {"Python","Rust"}
res = set1.symmetric_difference(set2)
print(f"set1,set2不重合集為{res}")
"""
判斷是否為子集
set_b.issubset(set_a)
即表示判斷set_b是否為set_a的子集
結果為布林值,即True或False
"""
set1 = {"Python","Go"}
set2 = {"Python"}
# set2是否為set1的子集
res = set2.issubset(set1)
print(res)
13、字典常用方法
# 空字典
a = {}
a = dict()
# 若字典沒有這個key,則會添加這對鍵值對
a["name"] = "Kwan"
a["age"] = 88
print(f"空字典添加兩個值后{a}")
a["age"] = 99
print(f"修改\"age\"的value{a}")
b = {"name": "Kwan", "age": 99}
b = dict(name="Kwan", age=99)
# dict類中引數不能使用數字,會報錯
# b = dict(name="Kwan",age=99,1="abc")
# 元組串列
tuple_list = [("name", "Kwan"), ("age", 99)]
c = dict(tuple_list)
print(f"元組串列生成的字典{c}")
# 所有key都賦予相同的值
key_list = ["name", "age"]
d = dict.fromkeys(key_list, "你猜")
print(f"所有key都賦予相同的值{d}")
"""
字典取值方法
1、dict.get(key,default_value)
1)若key不存在則回傳default_value
2)default_value默認為None
2、dict[key]
若key不存在,則報錯
"""
tmp_dict = {"name": "Kwan", "age": 88}
res1 = tmp_dict.get("name")
# res1 = tmp_dict["name"]
res2 = tmp_dict.get("sex", "未知性別")
# res2 = tmp_dict["sex"] 報錯
print(res1)
print(res2)
"""
獲取字典所有的key
dict.keys()
1、回傳值不是串列,是dict_keys物件
2、一般與for搭配使用
"""
tmp_dict = {"name": "Kwan", "age": 88}
res = tmp_dict.keys()
print(type(res))
for key in res:
print(key)
"""
獲取字典所有的value
dict.values()
1、回傳值不是串列,是dict_values物件
2、一般與for搭配使用
"""
tmp_dict = {"name": "Kwan", "age": 88}
res = tmp_dict.values()
print(type(res))
for value in res:
print(value)
"""
獲取字典所有的key和value
dict.items()
1、回傳值不是串列,是dict_items物件
2、一般與for搭配使用
"""
tmp_dict = {"name": "Kwan", "age": 88}
res = tmp_dict.items()
print(type(res))
# [(key1,value1),(key2,value2)]
for key, value in res:
print(f"key:{key},value:{value}")
"""
字典的更新
dict_a.update(dict_b)
可以新增新的鍵值對,也可修改已存在的鍵值對
"""
tmp1 = {"name": "Kwan", "age": "88"}
tmp2 = {"sex": "male", "age": 99}
tmp1.update(tmp2)
print(tmp1)
14、索引和切片
# 索引,超過變數長度-1就會報錯
# 1234567891011
a = "Hello, World"
a_len = len(a)
res = a[7]
print(f"a的長度為{a_len},a[7] = {res}")
# -6 -5 -4 -3 -2 -1 反向索引
# 0 1 2 3 4 5 正向索引
b = ["x", "y", "z", 1, 2, 3]
res = b[-1]
print(res)
# 切片,顧頭不顧尾
# [頭:尾:步長] 步長默認為1
# -6 -5 -4 -3 -2 -1 反向索引
# 0 1 2 3 4 5 正向索引
b = ["x", "y", "z", 1, 2, 3]
res1 = b[0:3] # 0到3之間的索引 不包括尾
# res1 = b[:3]
# res1 = b[-6:-3]
res2 = b[3:6]
res3 = b[::2] # 從頭取到尾,步長為2
res4 = b[::-2] # 從頭取到尾,步長為-2
res5 = b[::-1] # 從頭取到尾,步長為-1,串列翻轉
print(f"b[0:3] = {res1}")
print(f"b[3:6] = {res2}")
print(f"b[::2] = {res3}")
print(f"b[::-2] = {res4}")
print(f"b[::-1] = {res5}")
15、for回圈
# for ... in 回圈
weeks_list = ["周一", "周二", "周三"]
for week in weeks_list:
print(f"今天是{week}")
# 多個變數
date_list = [
["1月", "1號", "周一", "a"],
["2月", "2號", "周二", "a"],
["3月", "3號", "周三", "a"],
]
for month, date, _, _ in date_list:
print(f"今天是{month}---{date}")
# ["1月","1號","周一"],"a"
for *date_week, _ in date_list:
print(f"今天是{date_week}")
# "1月",["1號","周一"],"a"
for _, *date_week, _ in date_list:
print(f"今天是{date_week}")
# continue:立即結束本次回圈,進入下一次回圈
# break:終止回圈
# for ... else ...
# 當for回圈結束且不是因為break而終止時
# 才會執行else里的代碼
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in num_list:
if i % 2 == 0:
continue
print("這是偶數{i}")
elif i == 9:
print(f"遇到{i},結束回圈")
break
else:
print(i)
else:
print("本次此處for回圈正常執行完")
16、while回圈
a = 0
while a < 5:
a += 1
print(a)
a = 0
while a < 5:
a += 1
if a == 2:
continue
elif a == 4:
break
else:
print(a)
else:
print("while回圈正常執行結束")
while True:
print("無限回圈")
17、if三元&推導式
"""
if的三元寫法:
運算式1 if 條件 else 運算式2
條件為True則執行運算式1
條件為False則執行運算式2
"""
if len("test") > 5:
a = "長度大于5"
else:
a = "長度小于5"
a = "長度大于5" if len("test") > 5 else "長度小于5"
print(f"a = \"{a}\"")
"""
range(頭,尾,步長)
1、顧頭不顧尾,頭默認為0,步長默認為1
2、python2.x 回傳結果為串列
3、python3.x 回傳結果為range物件,可使用for遍歷
"""
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_range1 = range(10)
num_range2 = range(1, 11)
num_range3 = range(1, 11, 2)
num_range4 = range(2, 11, 2)
print(f"num_range1的資料型別{type(num_range1)}")
"""
串列、集合推導式
基本格式:
list = [運算式 for 變數名 in 序列 if 條件]
1) if條件,非必寫項
2) 若寫了if,只要滿足if的條件參會執行運算式
3) 并且不能跟else
"""
a = []
for i in range(1, 11):
a.append(i)
print(f"正常for回圈生成的整數串列\n{a}")
a = [i for i in range(1, 11)]
print(f"串列推導式生成的整數串列\n{a}")
o_list = [] # 求偶數串列
for i in range(1, 11):
if i % 2 == 0:
o_list.append(i)
print(f"正常for回圈生成的偶數串列\n{o_list}")
o_list = [
i for i in range(1, 11) if i % 2 == 0
]
print(f"帶if的推導式生成的偶數串列\n{o_list}")
o_list = [i for i in range(2, 11, 2)]
print(f"直接使用range步長和推導式生成的偶數串列\n{o_list}")
"""
字典推導式:
dict = {key: value for 變數名 in 序列 if 條件}
"""
tmp_list = [
("name", "a", "Kwan"),
("age", "b", 88)
]
tmp_dict = {}
for tmp_tuple in tmp_list:
tmp_dict[tmp_tuple[0]] = tmp_tuple[2]
print(f"正常for回圈生成的字典:\n{tmp_dict}")
tmp_dict = {
tmp_tuple[0]: tmp_tuple[2] for tmp_tuple in tmp_tuple
}
print(f"字典推導式生成的字典:\n{tmp_dict}")
18、函式的作用&定義
"""
def 函式名(形式引數):
代碼塊
return 結果
1、形式引數:非必須
2、return:非必須,默認回傳None
3、只要遇到return,函式呼叫就結束,立即回傳結果
"""
# 空函式
def tmp1():
pass # 占行
def tmp2():
return # 回傳值為None
def tmp3():
return None
def find_num(tmp_list):
res = []
for i in tmp_list:
if i.isdigit():
res.append(i)
return res
a = ["1", "2", "A", "3", "4", "f"]
res1 = find_num(a)
b = ["11", "21", "A1", "31", "41", "f1"]
res2 = find_num(b)
print(f"呼叫函式的執行結果\n{res1}")
print(f"呼叫函式的執行結果\n{res2}")
19、函式的引數
# 普通引數(必傳引數)
def cal_num(num1, num2):
res = num1 ** 2 + num2
return res
# 按順序傳參
test1 = cal_num(3, 1) # 3的二次方加1
print(test1)
test2 = cal_num(1, 3) # 1的二次方加3
print(test2)
# 指定傳參
test3 = cal_num(num2=1, num1=3)
# 默認引數必須放在普通引數后面
# def cal_num(num2=1,num1): 這樣會報錯
def cal_num_default(num1, num2=1):
res = num1 ** 2 + num2
return res
test4 = cal_num_default(3)
test5 = cal_num_default(3, 2)
test6 = cal_num_default(num2=2, num1=3)
# 不定長引數
def cal_sum(*rgs):
result = 0
for i in rgs:
result += i
return result
res1 = cal_sum(1, 2, 3)
res2 = cal_sum(1, 2, 3, 4, 5, 6, 7)
# 關鍵字引數
def cal_sum2(num, **kwargs):
result = num
for k, v in kwargs.items():
result += v
return result
# kwargs為字典{"num2":2,"num3":3}
res3 = cal_sum2(num2=2, num=1, num3=3)
# 命名關鍵字引數
def cal_sum3(num, *, num2, num3=3):
result = num + num2 + num3
return result
res4 = cal_sum3(num2=2, num=1)
res5 = cal_sum3(num2=2, num=1, num3=5)
"""
引數定義的順序必須是:
普通引數、默認引數、不定長引數、命名關鍵字引數、關鍵字引數
def cal(num1,num2,*args,*,num3,num3,**kwargs):
"""
20、多個回傳值
a = ["1", "2", "A", "3", "4", "f"]
def find_that1(tmp_list):
res1 = []
res2 = []
for i in tmp_list:
if i.isdigit():
res1.append(i)
elif i.isalpha():
res2.append(i)
return res1, res2
# return (res1, res2)
tmp_res = find_that1(a)
tmp_res1, tmp_res2 = find_that1(a)
# 回傳值不一定是代碼塊的值,可以是其他的值
def find_that2(tmp_list):
res1 = []
res2 = []
for i in tmp_list:
if i.isdigit():
res1.append(i)
elif i.isalpha():
res2.append(i)
return res1, res2, 1, 2, 3
tmp_res1, tmp_res2, *tmp_res3 = find_that2(a)
print(f"{tmp_res1},{tmp_res2},{tmp_res3}")
# return 1 + 2 有確切結果回傳值,沒有就None
21、作用域
total = 0 # 全域變數
def plus(a, b):
# 這里的total區域變數
total = a + b
print(f"函式內部區域變數total={total}")
plus(1, 2)
print(f"函式外部全域變total={total}")
def plus2(a, b):
# 在函式內部使用函式外部的全域變數total
global total
total = a + b
print(f"函式內部區域變數total={total}")
plus2(1, 2)
print(f"函式外部全域變total={total}")
def plus3(a, b):
# 在函式內部使用函式外部的全域變數total
tmp_num = 10
res = a + b + tmp_num
print(f"函式內部區域變數total={res}")
# 不能在函式外部使用函式內部定義的變數
tmp_num = tmp_num + 10
22、匿名函式
"""
匿名函式:沒有函式名
lambda 引數1,引數2...引數n : 運算式
"""
def plus1(num1, num2):
result = num1 + num2
return result
res1 = plus1(10, 11)
print("res1 = {}".format(res1))
plus2 = lambda x, y: x + y
res2 = plus2(10, 11)
print("res2 = {}".format(res2))
23、類的定義
"""
類(class):對具有相同屬性(property)和方法(method)的物件(object)進行的抽象層
物件(object):通過類進行實體化得到
例:手機、平板、筆記本電腦...
都屬于‘電子設備’這一類
都有的屬性:尺寸、電量...
都有的方法:刷劇、打游戲...
"""
# 繼承自object類
class Human(object):
# 初始化方法
def __init__(self, name, age=0):
self.name = name
self.age = age
self.ask = False
def run(self):
print("{}在跑步".format(self.name))
def sleep(self):
print("{}在睡覺".format(self.name))
# 實體化
human = Human(name="Kwan", age=88)
# 方法
human.run()
human.sleep()
# 屬性
human_age = human.age
print(f"年齡是{human_age}")
24、魔術方法
class Human(object):
# 構造方法 回傳結果為實體化的物件
def __new__(cls, *args, **kwargs):
print("觸發構造方法 __new__")
return super().__new__(cls)
# 初始化方法 無回傳值
def __init__(self, name, age=0):
print("觸發初始化方法 __init__")
self.name = name
self.age = age
self.ask = False
# 洗掉方法(析構方法) 無回傳值
# def 物件名 或 程式執行結束之后觸發
def __del__(self):
print("觸發洗掉方法 __def__")
# 呼叫方法 回傳值自定
# 把物件當作函式呼叫時觸發
def __call__(self, num):
print("觸發呼叫方法 __call__")
print(f"傳了一個{num}")
# 列印方法 回傳值必須是一個字串
# 使用print(物件)或者str(物件)的時候觸發
def __str__(self):
print("觸發列印方法 __str__")
return "列印了我"
def __len__(self):
print("觸發長度方法 __len__")
return 100
# 實體化
human = Human(name="Kwan", age=88)
human(99)
print(human)
len_human = len(human)
print(len_human)
25、類的繼承
"""
類的繼承
1、子類會繼承父類的所有屬性和方法
2、一個類可以繼承自多個類
3、子類可以重寫父類中的方法和屬性
4、當繼承多個父類且父類中有相同方法,
就按照從左到右的先后順序來決定使用哪個父類的方法
# 如A、B、C三個父類都有run(),那么class D(B,A,C)就會默認B中的run()
"""
class Human(object):
def __init__(self, name, age=0):
self.name = name
self.age = age
def run(self):
print("{}在跑步".format(self.name))
def work(self):
print("{}在搬磚".format(self.name))
def sleep(self):
print("{}在睡覺".format(self.name))
class Money(object):
def work(self):
print("錢錢在自己搬自己")
# class Worker(Human, Money):
# def sleep(self):
# print("{}歲的{}怎么睡的著啊".format(self.name, self.age))
class Worker(Money, Human):
def sleep(self):
print("{}歲的{}怎么睡的著啊".format(self.name, self.age))
worker = Worker(name="Kwan", age=88)
print(worker.name, worker.age)
worker.run()
worker.work()
worker.sleep()
26、靜態方法和類方法
"""
靜態方法:
1、在方法的上方使用裝飾器 @staticmethod 即可
2、沒有self引數,也沒有cls引數
3、可以不經過實體化,直接使用
類方法:
1、在方法的上方使用裝飾器 @classmethod 即可
2、有cls引數,代筆類本身
3、可以不經過實體化,直接使用
類方法:能訪問類的屬性,不能訪問__init__中初始化的屬性
靜態方法:不能訪問累的屬性,不能訪問__init__中初始化的屬性
"""
class Human:
desc = "這是一個Human類"
def __init__(self, name="xxx", age="xxx"):
self.name = name
self.__age = age
@classmethod
def info(cls):
print(cls.desc)
@staticmethod
def eat():
print("吃飯")
Human.eat()
Human.info()
27、方法和函式
"""
1、函式和靜態方法,都是函式型別(function)
2、實體方法和類方法,都是方法型別(method)
"""
def tmp():
pass
class Human:
desc = "這里一個Human類"
def __init__(self,name,age = 0):
self.name = name
self.__age = age
def run(self):
print("{}在跑步".format(self.name))
@classmethod
def info(cls):
print(cls.desc)
@staticmethod
def eat():
print("吃飯")
human = Human(name="Kwan",age=88)
print(f"實體方法run的型別為{type(human.run)}")
print(f"類方法info的型別為{type(human.info)}")
print(f"靜態方法eat的型別為{type(human.eat)}")
print(f"函式tmp的型別為{type(tmp)}")
28、私有化
"""
私有屬性和私有方法
1、以雙下劃線__開頭
2、僅可在類的內部使用
"""
class Human:
desc = "這里一個Human類"
def __init__(self,name,age = 0):
self.name = name
self.__age = age
def __run(self):
print("{}在跑步".format(self.name))
def sleep(self):
self.__run()
print("{}歲的{}在睡覺".format(self.__age,self.name))
human = Human(name="Kwan",age=88)
human.sleep()
human.__run()
print(human.__age)
29、property裝飾器
"""
在方法的上方添加@property
作用:將方法轉為屬性
"""
class Human:
desc = "這是一個Human類"
def __init__(self,height=1.7,weight=60):
self.height = height
self.weight = weight
@property
def bmi(self):
"""
BMI指數:體重(kg)/身高(m)的平方
"""
return self.weight / self.height ** 2
def eat(self):
print("吃飯")
human = Human(height=1.88,weight=80)
bmi_val = human.bmi # 可以想屬性一樣呼叫了
print(f"BMI = {bmi_val}")
human.eat()
30.1、例外捕獲
"""
例外捕獲
try:
執行代碼
except 錯誤型別 as 別名:
發生例外時執行的代碼
else:
沒有例外時執行的代碼
finally:
無論有沒有例外都會執行的代碼
try/except陳述句: else和finally可有可無
try/finally陳述句:else和except可有可無
"""
try:
a = 5
b = "y"
c = a / b
# except(ValueError,TypeError,NameError)
except Exception as e:
# 萬能錯誤型別:Exception
print(f"出現例外:{e}")
except ValueError as v:
print(f"出現例外:{v}")
else:
print("沒出現例外")
finally:
print("無論有沒有例外都會執行")
30.2、拋出例外
"""
raise 錯誤型別(錯誤資訊)
"""
a = 1 + 1
if a == 2:
raise Exception("主動拋出例外")
# 自定義錯誤型別
class SpecialError(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return f"出現特殊例外:{self.msg}"
raise SpecialError("未知錯誤")
30.3、斷言
"""
assert 運算式,例外資訊
1、例外資訊可有可無
2、運算式的結果一定要是布林值,即True或者False
等價于:
if not 運算式:
raise AssertionError(例外資訊)
"""
assert 1 != 1, "肯定錯了,1當然等于1"
31、可變物件和不可變物件
"""
可變物件:list、set、dict
不可變物件:int、float、string、tuple
不可變:物件的內容是不能改變的,
但是變數的物件參考是可變的
"""
# 次數變數a ---> "hello"
a = "hello"
print(f"a = {a}")
# 等號右邊運行結果為"hello world" 新創建的字串
# 此時變數a --x--> "hello"
# a -----> "hello world"
# "hello"會被垃圾回識訓制清理
a = a + "world"
print(f"a = {a}")
# 此時 b[2] ---> 串列記憶體地址
# 串列記憶體地址 ---> [4,5,6]
b = (1, 2, [4, 5, 6])
print(f"b = {b}")
# 此時 b[2] ---> 串列記憶體地址(沒變)
# 串列記憶體地址 ---> [7,5,6]
b[2][0] = 7
print(f"b = {b}")
32、生成器
a = [i for i in range(3)] # 串列生成式
b = (i for i in range(3)) # 生成器
print(type(b))
def generator():
tmp = [i for i in range(1000000)]
index = 0
while index < len(tmp):
print(f"當前值:{tmp[index]}")
index = index + 1
yield tmp[index]
raise StopIteration
gen = generator()
print(type(gen))
# 也可以使用for回圈不斷地執行next(gen)
next(gen)
# 可以通過send方法觸發next
gen.send(None)
33、可迭代物件&迭代器物件
"""
1、可迭代物件:實作了__iter__()或__getitem__()
iterable
2、迭代器物件:實作了__iter__()和__next___()
iterator
3、使用函式iter(iterable),即可獲得迭代器物件
"""
class Array:
def __init__(self,init_list,index = 0):
self.init_list = init_list
self.index = index
def __iter__(self):
"""回傳值必須為一個迭代器物件"""
return iter(self.init_list)
def __getitem__(self, i):
"""回傳對應索引的元素"""
return self.init_list[i]
def __next__(self):
if self.index > len(self.init_list) - 1:
raise StopIteration
self.index += 1
return self.init_list[self.index]
# 實體化得到一個可迭代物件
tmp = Array([1,2,3])
# 轉換為迭代器物件
# gen = tmp.__iter__()
gen = iter(tmp)
# 使用next往后取值,超出長度則拋出例外
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
34、裝飾器
"""
裝飾器的作用:在不改變原函式的情況下增加功能
"""
# 不帶引數的函式裝飾器
def decorator(func):
def run(*args, **kwargs):
print("運行原函式之前")
func()
print("運行原函式之后")
return run
@decorator
def start():
print("開始運行")
start()
# 帶引數的函式裝飾器
def who(name):
def decorator(func):
def run():
print(f"傳入了{name}")
print("運行原函式之前")
func()
print("運行原函式之后")
return run
return decorator
@who(name=921)
def start():
print("開始運行")
start()
# 不帶引數的類裝飾器
class decorator:
def __init__(self,func):
self.func = func
def __call__(self, *args, **kwargs):
print("運行原函式之前")
self.func(*args,**kwargs)
print("運行原函式之后")
@decorator
def start():
print("開始運行")
start()
# 帶引數的類裝飾器
class decorator:
def __init__(self,name):
self.name = name
def __call__(self, func):
def inner(*args,**kwargs):
print(self.name)
print("運行原函式之前")
func(*args,**kwargs)
print("運行原函式之后")
return inner
@decorator(name = "921")
def start():
print("開始運行")
start()
35、包和模塊
"""
1、package(包):
一個包就是一個檔案夾
只不過檔案夾里面有一個__init__.py檔案
2、module(模塊):
一個模塊就是一個.py檔案
3、第三方模塊:
官網:https://pypi.org/
終端命令:
安裝 pip install XXX,XXX
pip3 install XXX,XXX
卸載 pip uninstall XXX,XXX
查看 pip list
第一次用記得改源
模塊匯入
import time
from time import time_ns
"""
"""
1.py
def plus(x,y):
return x + y
2.py
from 1 import plus
A = 1
B = 2
print(plus(A,B))
# 不能互相匯入
"""
36、with
"""
with:背景關系管理
"""
# 獲取一個檔案物件
fp = open("./test.txt","r")
res1 = fp.read()
print(f"讀取結果:\n{res1}")
# 檔案物件使用完畢后一點要關閉
fp.close()
with open("./text.txt","r") as fp:
res1 = fp.read()
print(f"讀取結果:\n{res1}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/551897.html
標籤:其他
下一篇:返回列表
