內容全干貨,不說廢話,代碼講解都在注釋哦,希望挨個看著敲一遍,不要復制粘貼哦,
本基礎分為十個部分:
1-數字
2-字串
3-串列
4-控制流
5-函式
6-資料結構
7-模塊
8-深層輸入與輸出
9-例外和錯誤
10-類
11-標準庫簡介
12-協程
為懶人準備,如果需要下載這些代碼,本專案github鏈接下載即可:
https://github.com/89461561511656/Introduction-to-python3.9.git
為小白準備的交流群:
970353786
為python愛好者準備的專案鏈接:qq機器人
https://www.cnblogs.com/aisisi/p/15055168.html
mysql資料庫入門到精通學習鏈接:
https://blog.csdn.net/weixin_46211269/article/details/119086242?spm=1001.2014.3001.5501
第一部分:數字
"""
作者:川川
時間:2021/7/27
"""
#加減
# a=2
# b=2
# c=a-b
#d=a-b
# print(c,d)
#乘除
# a=(50-5*6)/4
# print(a)
# a=8/5
# print(a)
'''/回傳為float,//回傳整數,%回傳余數'''
# a=17/3
# print(a)
# a=17//3
# print(a)
# a=5*3+2
# print(a)
'''冪運算 **'''
# a=4**2
# b=2**3
# print(a,b)
第二部分:字串
"""
作者:川川
時間:2021/7/27
"""
'''單引號和雙引號效果相同 反斜杠 \ 用于轉義'''
# a='spam eggs'
# b='doesn\'t'
# c="\"Yes,\" they said."
# print(a)
# print(b)
# print(c)
'''如果不希望前置 \ 的字符轉義成特殊字符,可以使用 原始字串,在引號前添加 r '''
#比如說我們路徑問題
# c=r'C:\some\name'
# print(c)
# print(r'C:\some\name')
'''三引號使用'''
# print("""\
# Usage: thingy [OPTIONS]
# -h Display this usage message
# -H hostname Hostname to connect to
# """)
'''字串可以用 + 合并(粘到一起),也可以用 * 重復'''
# a='how are '+'you'
# b='zhu'
# c=b*3
# print(a)
# print(c)
'''相鄰的兩個或多個 字串字面值 (引號標注的字符)會自動合并'''
# a= 'Py' 'thon'
# print(a)
'''拆分長字串'''
# text = ('Put several strings within parentheses '
# 'to have them joined together.')
# print(text)
######### 切片#########
'''字串支持 索引 (下標訪問),第一個字符的索引是 0,'''
# word = 'Python'
# print(word[0],word[2])
'''索引還支持負數,用負數索引時,從右邊開始計數'''
# print(word[-1],word[-2])
# text='s'
# print(text[0])
'''除了索引,字串還支持 切片,輸出結果包含切片開始,但不包含切片結束'''
# print(word[0:2])
# print(word[0:5])
'''省略開始索引時,默認值為 0,省略結束索引時,默認為到字串的結尾'''
# print(word[:2])
# print(word[4:])
# print(word[-2:])
'''切片會自動處理越界索引'''
# print(word[4:42])
# print(word[42:])
''' 字串不能修改'''
# word[0] = 'J'#錯誤
'''要生成不同的字串,應新建一個字串'''
# z='J' + word[1:]
# print(z)
'''內置函式 len() 回傳字串的長度,一個空格也算一個長度'''
# s = 'supercalifragilisticexpia lidocious'
# print(len(s))
第三部分:串列
"""
作者:川川
時間:2021/7/27
"""
# squares = [1, 4, 9, 16, 25]
# print(squares)
'''支持索引和切片'''
# print(squares[1])
# print(squares[-1])
# print(squares[-3:])
'''串列還支持合并操作'''
# c=squares + [36, 49, 64, 81, 100]
# print(c)
'''串列內容可修改'''
# cubes = [1, 8, 27, 65, 125]
# cubes[3] = 64
# print(cubes)
'''append() 方法 可以在串列結尾添加新元素'''
# cubes.append(216)
# cubes.append(7 ** 3)
# print(cubes)
'''切片賦值可以改變串列大小,甚至清空整個串列'''
# letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# print(letters)
# letters[2:5] = ['C', 'D', 'E']
# print(letters)
# letters[2:5] = []
# print(letters)
# letters[:] = []
# print(letters)
'''內置函式 len() 也支持串列'''
# letters = ['a', 'b', 'c', 'd']
# print(len(letters))
'''還可以嵌套串列(創建包含其他串列的串列)'''
# a = ['a', 'b', 'c']
# n = [1, 2, 3]
# x = [a, n]
# print(x)
# print(x[0])#索取
# print(x[0][1])
#while
'''斐波納契數列,使得每個數字是兩個前述者的總和,選自0和1,'''
# a, b = 0, 1
# while a < 10:
# print(a)
# a, b = b, a + b
'''print'''
# i = 256*256
# print('The value of i is', i)
'''end 可以取消輸出后面的換行, 或用另一個字串結尾'''
# a, b = 0, 1
# while a < 1000:
# print(a, end=',')
# a, b = b, a + b
第四部分:控制流
"""
作者:川川
時間:2021/7/27
"""
'''if陳述句固定搭配'''
# x = int(input("Please enter an integer: "))
# if x < 0:
# x = 0
# print('Negative changed to zero')
# elif x == 0:
# print('Zero')
# elif x == 1:
# print('Single')
# else:
# print('More')
'''if ... elif ... elif ... 序列看作是其他語言中 switch 或 case 陳述句的替代品,'''
'''for陳述句'''
# words = ['cat', 'window', 'defenestrate']
# for w in words:
# # print(w, len(w))
''' range() 函式用于遍歷數字序列'''
# for i in range(5):
# print(i)
'''range包左不包右'''
# for i in range(5, 10):
# print(i)
'''range 可以不從 0 開始,還可以按指定幅度range(起點,終點,步長)'''
# for i in range(0, 10, 3):
# print(i)
# for j in range(-10, -100, -30):
# print(j)
'''range() 和 len() 組合在一起,可以按索引迭代序列'''
# a = ['Mary', 'had', 'a', 'little', 'lamb']
# for i in range(len(a)):
# print(i, a[i])
'''使用sum和range求連加和'''
# print(sum(range(5))) #0 + 1 + 2 + 3+4
'''range 生成串列解決'''
# print(list(range(4)))
'''質數判斷'''
#仔細看:else 子句屬于 for 回圈,不屬于 if 陳述句,
# for n in range(2, 10):
# for x in range(2, n):
# if n % x == 0:
# print(n, 'equals', x, '*', n // x)
# break
# else:
# print(n, 'is a prime number')
'''continue 陳述句也借鑒自 C 語言,表示繼續執行回圈的下一次迭代:'''
# for num in range(2, 10):
# if num % 2 == 0:
# print("Found an even number", num)
# continue
# print("Found an odd number", num)
#pass
'''pass 陳述句不執行任何操作'''
# while True:
# pass
'''下面這段代碼創建了一個最小的類'''
# class MyEmptyClass:
# pass
'''pass 還可以用作函式或條件子句的占位符'''
# def initlog(*args):
# pass
第五部分:函式
"""
作者:川川
時間:2021/7/27
"""
'''def 定義函式 斐波那契數列函式'''
# def fib(n):
# a, b = 0, 1
# while a < n:
# print(a, end=' ')
# a, b = b, a + b
# print()
# fib(100) #傳參
#回傳串列
# def fib2(n):
# result = []
# a, b = 0, 1
# while a < n:
# result.append(a)
# a, b = b, a + b
# return result
# f100 = fib2(100)
# print(f100)
'''默認值在 定義 作用域里的函式定義中求值'''
# i = 5
# def f(arg=i):
# print(arg)
# i = 6
# f()#輸出5而不是6
'''默認值為串列、字典或類實體等可變物件時,會產生與該規則不同的結果,'''
# def f(a, L=[]):
# L.append(a)
# return L
# print(f(1))
# print(f(2))
# print(f(3))
'''不想在后續呼叫之間共享默認值時,應以如下方式撰寫函式'''
# def f(a, L=None):
# if L is None:
# L = []
# L.append(a)
# return L
# print(f(10))
# print(f(11))
"""關鍵字引數"""
# 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, "!")
# # parrot(5)
# '''該函式接受一個必選引數(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
'''*name 必須在 **name 前面'''
# def cheeseshop(kind, *arguments, **keywords):
# print("-- Do you have any", kind, "?")
# print("-- I'm sorry, we're all out of", kind)
# for arg in arguments:
# print(arg)
# print("-" * 40)
# for kw in keywords:
# print(kw, ":", keywords[kw])
# cheeseshop("Limburger", "It's very runny, sir.",
# "It's really very, VERY runny, sir.",
# shopkeeper="Michael Palin",
# client="John Cleese",
# sketch="Cheese Shop Sketch")
'''some example'''
# def standard_arg(arg):
# print(arg)
# def pos_only_arg(arg, /):
# print(arg)
# def kwd_only_arg(*, arg):
# print(arg)
# def combined_example(pos_only, /, standard, *, kwd_only):
# print(pos_only, standard, kwd_only)
#來看看區別
#第一個對呼叫方式沒有任何限制,可以按位置也可以按關鍵字傳遞引數
# print(standard_arg(2))
# print(standard_arg(arg=2))
#第二個 函式定義中有 /,僅限使用位置形參
# print(pos_only_arg(1))
# print(pos_only_arg(arg=1))#就會報錯
#第三個 函式定義通過 * 表明僅限關鍵字引數
# print(kwd_only_arg(3))#就會報錯
# print(kwd_only_arg(arg=3))
#第四個kwd_only_arg(arg=3)
# print(combined_example(1, 2, 3))#報錯
# print(combined_example(1, 2, kwd_only=3))
# print(combined_example(1, standard=2, kwd_only=3))
# print(combined_example(pos_only=1, standard=2, kwd_only=3))#報錯
'''加上 / (僅限位置引數)后,就可以了,此時,函式定義把 name 當作位置引數,'name' 也可以作為關鍵字引數的鍵'''
# def foo(name, /, **kwds):
# return 'name' in kwds
# print(foo(1, **{'name': 2}))#回傳tuue
# def foo(name, **kwds):
# return 'name' in kwds
# print(foo(name=5))#回傳false,實際這name沒用到,所以喲弄個上面那個方法
'''解包實參串列'''
# print(list(range(3, 6)))
# args = [3, 6]
# print(list(range(*args)))#用 * 運算子把實參從串列或元組解包出來
'''字典可以用 ** 運算子傳遞關鍵字引數'''
# def parrot(voltage, state='a stiff', action='voom'):
# print("-- This parrot wouldn't", action, end=' ')
# print("if you put", voltage, "volts through it.", end=' ')
# print("E's", state, "!")
# d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
# parrot(**d)
"""Lambda 運算式"""
'''lambda a, b: a+b 函式回傳兩個引數的和'''
# def make_incrementor(n):
# return lambda x: x + n
# f = make_incrementor(42)
# print(f(0))
# print(f(1))
第六部分:資料結構
"""
作者:川川
時間:2021/7/27
"""
"""5.1 串列詳解"""
# fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
'''
list.count(x)
回傳串列中元素 x 出現的次數
'''
# print(fruits.count('apple'))
'''
list.index(x[, start[, end]])
回傳串列中第一個值為 x 的元素的零基索引位置,第一個!
'''
# print(fruits.index('banana'))
# print(fruits.index('banana', 4,7))
'''
list.reverse()
反轉串列中的元素,
'''
# fruits.reverse()
# print(fruits)
'''
list.append(x)
在串列末尾添加一個元素
'''
# fruits.append('grape')
# print(fruits)
'''
list.sort(*, key=None, reverse=False)
就地排序串列中的元素
'''
# fruits.sort()
# print(fruits)
'''
list.pop([i])
洗掉串列中指定位置的元素,并回傳被洗掉的元素,未指定位置時,a.pop() 洗掉并回傳串列的最后一個元素,
'''
# fruits.pop()#默認洗掉最后一個
# print(fruits)
# fruits.pop(0)#洗掉第一個
# print(fruits)
'''
list.copy()
回傳串列的淺拷貝,復制
'''
# fruits.copy()
# print(fruits)
'''
list.clear()
洗掉串列里的所有元素,相當于 del a[:] ,
'''
# fruits.clear()
# print(fruits)
'''
list.remove(x)
從串列中洗掉第一個值為 x 的元素,未找到指定元素時,觸發 ValueError 例外,
'''
# fruits.remove('apple')
# print(fruits)
'''
list.insert(i, x)
在指定位置插入元素,第一個引數是插入元素的索引,因此,a.insert(0, x) 在串列開頭插入元素
'''
# fruits.insert(1, 'nana')
# print(fruits)
'''用串列實作堆疊'''
'''
特點:“后進先出” 把元素添加到堆疊的頂端,使用 append() ,從堆疊頂部取出元素,使用 pop() ,不用指定索引,
'''
# stack = [3, 4, 5]
# stack.append(6)
# stack.append(7)
# print(stack)
# stack.pop()
# print(stack)
# stack.pop()
# print(stack)
'''用串列實作佇列'''
'''特點:“先進先出” 實作佇列最好用 collections.deque,可以快速從兩端添加或洗掉元素'''
# from collections import deque
# queue = deque(["Eric", "John", "Michael"])
# queue.append("Terry")
# queue.append("Graham")
# print(queue)
# print(queue.popleft())#第一個
# print(queue.popleft())#第二個
# print(queue)
''''串列推導式'''
'''創建平方值的串列'''
# squares = []
# for x in range(10):
# squares.append(x ** 2)
# print(squares)
# b=squares = [x**2 for x in range(10)]
# print(b)
# a=squares = list(map(lambda x: x**2, range(10)))
# print(a)#同上
'''串列推導式將兩個串列中不相等的元素組合起來'''
# a=[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
# print(a)
'''等價如下'''
# combs = []
# for x in [1,2,3]:
# for y in [3, 1, 4]:
# if x != y:
# combs.append((x, y))
# print(combs)
'''some example'''
# vec = [-4, -2, 0, 2, 4]
# print([x*2 for x in vec])
# print([x for x in vec if x >= 0])
# print([abs(x) for x in vec])#abs求絕對值
# freshfruit = [' banana', ' loganberry ', 'passion fruit ']
# a=[weapon.strip() for weapon in freshfruit]
# print(a)
'''!!!!運算式是元組(例如上例的 (x, y))時,必須加上括號'''
# b=[(x, x**2) for x in range(6)]
# print(b)
'''串列推導式可以使用復雜的運算式和嵌套函式'''
# from math import pi
# a=[str(round(pi, i)) for i in range(1, 6)]
# print(a)
'''嵌套的串列推導式'''
# matrix = [
# [1, 2, 3, 4],
# [5, 6, 7, 8],
# [9, 10, 11, 12],
# ]
# a=[[row[i] for row in matrix] for i in range(4)]
# print(a)
#等價如下
# transposed = []
# for i in range(4):
# transposed.append([row[i] for row in matrix])
# print(transposed)
'''5.2del 陳述句 移除元素'''
# a = [-1, 1, 66.25, 333, 333, 1234.5]
# del a[1]
# print(a)
# del a[2:4]
# print(a)
# del a[:]
# print(a)
'''del 也可以用來洗掉整個變數'''
# del a[:]
# print(a)
'''5.3元組和序列'''
'''元組由多個用逗號隔開的值組成'''
# t = 12345, 54321, 'hello!'#輸入時,圓括號可有可無,不過經常是必須的
# print(t[0])
# print(t) #輸出時,元組都要由圓括號標注,這樣才能正確地解釋嵌套元組
# empty = ()
# singleton = 'hello', #注意不加逗號就成了字串了
# print(len(empty))
# print(len(singleton))
# print(singleton)
'''5.4集合'''
'''創建空集合只能用 set(),不能用 {},{} 創建的是空字典'''
# basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
# print(basket)
# print('orange' in basket)
# a = set('abracadabra')
# b = set('alacazam')
# print(a)
# print(a-b)
# print(a|b)#并集 letters in a or b or both
# print(a & b)#交集 etters in both a and b
# print( a ^ b)# # letters in a or b but not both
'''集合也支持推導式'''
# a = {x for x in 'abracadabra' if x not in 'abc'}
# print(a)
'''5.5字典'''
# tel = {'jack': 4098, 'sape': 4139}
# tel['guido'] = 4127 #添加
# print(tel)
# print(tel['jack'])#索取
# del tel['sape']
# tel['irv'] = 4127
# print(tel)
# print(list(tel))#轉換為串列
# print('guido' in tel)
'''dict() 建構式可以直接用鍵值對序列創建字典'''
# a=dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
# print(a)
# print(a['sape'])
'''字典推導式可以用任意鍵值運算式創建字典'''
# a={x: x**2 for x in (2, 4, 6)}#lamda
# print(a)
'''關鍵字是比較簡單的字串時,直接用關鍵字引數指定鍵值對更便捷'''
# c=dict(sape=4139, guido=4127, jack=4098)
# print(c)
# print(c['jack'])
'''5.6回圈的技巧'''
'''在字典中回圈時,用 items() 方法可同時取出鍵和對應的值'''
# knights = {'gallahad': 'the pure', 'robin': 'the brave'}
# for k, v in knights.items():
# print(k,v)
'''在序列中回圈時,用 enumerate() 函式可以同時取出位置索引和對應的值'''
# for i, v in enumerate(['tic', 'tac', 'toe']):
# print(i,v)
'''同時回圈兩個或多個序列時,用 zip() 函式可以將其內的元素一一匹配'''
# questions = ['name', 'quest', 'favorite color']
# answers = ['lancelot', 'the holy grail', 'blue']
# for q, a in zip(questions, answers):
# print('What is your {0}? It is {1}.'.format(q, a))#0和1只是占位,不起作用,可以空著
'''逆向回圈序列時,先正向定位序列,然后呼叫 reversed() 函式'''
# for i in reversed(range(1, 10, 2)):
# print(i)
'''按指定順序回圈序列,可以用 sorted() 函式,在不改動原序列的基礎上,回傳一個重新的序列'''
# basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
# for i in sorted(basket):
# print(i)
'''使用 set() 去除序列中的重復元素,使用 sorted() 加 set() 則按排序后的順序,回圈遍歷序列中的唯一元素'''
# basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
# for f in sorted(set(basket)):
# print(f)
'''一般來說,在回圈中修改串列的內容時,創建新串列比較簡單,且安全'''
# import math
# raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
# filtered_data = []
# for value in raw_data:
# if not math.isnan(value):
# filtered_data.append(value)
# print(filtered_data)#篩選出數字
'''5.7. 深入條件控制?'''
'''布爾運算子 and 和 or 也稱為 短路 運算子:其引數從左至右決議,一旦可以確定結果,決議就會停止,'''
# string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
# non_null = string1 or string2 or string3
# print(non_null)#回傳一個值
第七部分:模塊
"""
作者:川川
時間:2021/7/27
"""
'''用文本編輯器在當前目錄下創建 fibo.py 檔案,輸入以下內容'''
#這部分單獨創建檔案!在這展示fibo內容只是便于好看
# def fib(n): # write Fibonacci series up to n
# a, b = 0, 1
# while a < n:
# print(a, end=' ')
# a, b = b, a+b
# print()
#
# def fib2(n): # return Fibonacci series up to n
# result = []
# a, b = 0, 1
# while a < n:
# result.append(a)
# a, b = b, a+b
# return result
'''這項操作不直接把 fibo 函式定義的名稱匯入到當前符號表,只匯入模塊名 fibo ,要使用模塊名訪問函式'''
# import fibo
# print(fibo.fib(1000))
'''如果經常使用某個函式,可以把它賦值給區域變數'''
# a = fibo.fib
# print(a(400))
'''6.1. 模塊詳解'''
'''import 陳述句有一個變體,可以直接把模塊里的名稱匯入到另一個模塊的符號表'''
# from fibo import fib, fib2
# print(fib(500))
'''還有一種變體可以匯入模塊內定義的所有名稱 不建議從模塊或包內匯入 *, 因為,這項操作經常讓代碼變得難以理解,'''
# from fibo import *
# print(fib(500))
'''模塊名后使用 as 時,直接把 as 后的名稱與匯入模塊系結,意思就是改變名稱使用,'''
# import fibo as fib
# print(fib.fib(500))
'''from 中也可以使用這種方式'''
# from fibo import fib as fibonacci
# print(fibonacci(500))
第八部分:深層輸入輸出
"""
作者:川川
時間:2021/7/27
"""
'''在字串開頭的引號/三引號前添加 f 或 F ,在這種字串中,可以在 { 和 } 字符之間輸入參考的變數'''
# year = 2021
# event = 'Referendum'
# a=f'Results of the {year} {event}'
# print(a)
'''str.format() 該方法也用 { 和 } 標記替換變數的位置a 這種方法支持詳細的格式化指令'''
# yes_votes = 42_572_654
# no_votes = 43_132_495
# percentage = yes_votes / (yes_votes + no_votes)
# a='{:-5} YES votes {:1.1%}'.format(yes_votes, percentage)#調整{}內部感受下
# print(a)
'''只想快速顯示變數進行除錯,可以用 repr() 或 str() 函式把值轉化為字串,'''
# s = 'Hello, world.'
# print(str(s))#str() 函式回傳供人閱讀的值
# print(repr(s))#repr() 則生成適于解釋器讀取的值
# print(str(1/7))
# hellos = repr('hello')
# print(hellos)
'''7.1.1. 格式化字串字面值'''
'''格式化字串字面值 (簡稱為 f-字串)在字串前加前綴 f 或 F,通過 {expression} 運算式,把 Python 運算式的值添加到字串內'''
'''下例將 pi 舍入到小數點后三位'''
# import math
# print(f'The value of pi is approximately {math.pi:.3f}.')
'''在 ':' 后傳遞整數,為該欄位設定最小字符寬度,常用于列對齊'''
# table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
# for name, phone in table.items():
# print(f'{name:10} ==> {phone:10d}')
'''7.1.2. 字串 format() 方法'''
# print('We are the {} who say "{}!"'.format('knights', 'Ni'))
'''花括號及之內的字符(稱為格式欄位)被替換為傳遞給 str.format() 方法的物件,花括號中的數字表示傳遞給 str.format() 方法的物件所在的位置,'''
# print('{0} and {1}'.format('spam', 'eggs'))
# print('{1} and {0}'.format('spam', 'eggs'))
'''使用關鍵字引數名參考值,'''
# print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))
'''位置引數和關鍵字引數可以任意組合'''
# print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
# other='Georg'))
'''用方括號 '[]' 訪問鍵來完成'''
# table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
# print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(table))
'''也可以用 '**' 符號,把 table 當作傳遞的關鍵字引數,'''
# print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
'''生成一組整齊的列,包含給定整數及其平方與立方'''
# for x in range(1, 11):
# print('{0:2d} {1:3d} {2:4d}'.format(x, x * x, x * x * x))
'''7.1.3. 手動格式化字串'''
# for x in range(1, 11):
# print(repr(x).rjust(2), repr(x * x).rjust(3), end=' ')
# print(repr(x * x * x).rjust(4))
'''7.1.4. 舊式字串格式化方法'''
# import math
# print('The value of pi is approximately %5.3f.' % math.pi)
'''7.2. 讀寫檔案?'''
'''最常用的引數有兩個: open(filename, mode)'''
# f = open('workfile', 'w')
'''
第一個實參是檔案名字串第二個實參是包含描述檔案使用方式字符的字串,
mode 的值包括 'r' ,表示檔案只能讀取;'w' 表示只能寫入(現有同名檔案會被覆寫);
'a' 表示打開檔案并追加內容,任何寫入的資料會自動添加到檔案末尾,'r+' 表示打開檔案進行讀寫,
mode 實參是可選的,省略時的默認值為 'r',
'''
# with open('workfile') as f:
# read_data = f.read()
# print(read_data)
# f.close()#如果沒有使用 with 關鍵字,則應呼叫 f.close() 關閉檔案,即可釋放檔案占用的系統資源,
# with open('workfile') as f:
# a=f.read()
# print(a)
# f.close()
'''f.readline() 從檔案中讀取單行資料'''
# with open('workfile') as f:
# a=f.readline()
# b=f.readline()
# c=f.readline()
# print(a,b,c)
# for i in f:
# print(i)
# f.close()
'''從檔案中讀取多行時,可以用回圈遍歷整個檔案物件'''
# with open('workfile') as f:
# for line in f:
# print(line, end='')
# f.close()
'''f.write(string) 把 string 的內容寫入檔案,并回傳寫入的字符數,'''
# with open('workfile','w') as f:
# f.write('This is a test\n')
# f.close()
'''寫入其他型別的物件前,要先把它們轉化為字串(文本模式)或位元組物件(二進制模式)'''
# with open('workfile','a') as f:
# value = ('the answer', 42)
# s = str(value)
# f.write(s)
# f.close()
# f = open('workfile', 'rb+')
# f.write(b'0123456789abcdef')
# print(f.read())
# print(f.seek(5))
# print(f.read(1))
'''7.2.2. 使用 json 保存結構化資料'''
# import json
# a=json.dumps([1, 'simple', 'list'])
# print(a)
'''dumps() 函式還有一個變體, dump() ,它只將物件序列化為 text file '''
#如果 f 是 text file 物件
# json.dump(x, f)
#要再次解碼物件,如果 f 是已打開、供讀取的 text file 物件
# x = json.load(f)
第九部分:例外和錯誤
"""
作者:川川
時間:2021/7/27
"""
'''處理例外搭配:try except'''
'''如果沒有例外發生,則跳過 except 子句 并完成 try 陳述句的執行,'''
# while True:
# try:
# x = int(input("Please enter a number: "))
# break
# except ValueError:
# print("Oops! That was no valid number. Try again...")
'''一個 try 陳述句可能有多個 except 子句,以指定不同例外的處理程式,'''
# class B(Exception):
# pass
#
# class C(B):
# pass
#
# class D(C):
# pass
#
# for cls in [B, C, D]:
# try:
# raise cls()
# except D:
# print("D")
# except C:
# print("C")
# except B:
# print("B")
'''最后的 except 子句可以省略例外名,以用作通配符'''
# try:
# f = open('workfile')
# s = f.readline()
# i = int(s.strip())
# except OSError as err:
# print("OS error: {0}".format(err))
# except ValueError:
# print("Could not convert data to an integer.")
# except:
# print("Unexpected error:", sys.exc_info()[0])
# raise
'''try ... except 陳述句有一個可選的 else 子句,在使用時必須放在所有的 except 子句后面'''
# import sys
# for arg in sys.argv[1:]:
# try:
# f = open(arg, 'r')
# except OSError:
# print('cannot open', arg)
# else:
# print(arg, 'has', len(f.readlines()), 'lines')
# f.close()
'''處理 try 子句中呼叫(即使是間接地)的函式內部發生的例外,'''
# def this_fails():
# x = 1 / 0
# try:
# this_fails()
# except ZeroDivisionError as err:
# print('Handling run-time error:', err)
'''raise 陳述句支持強制觸發指定的例外'''
# try:
# raise NameError('HiThere')
# except NameError:
# print('An exception flew by!')
# raise
'''例外鏈'''
# def func():
# raise IOError
# try:
# func()
# except IOError as exc:
# raise RuntimeError('Failed to open database') from exc
'''例外鏈在 except 或 finally 子句觸發例外時自動生成'''
# try:
# open('database.sqlite')
# except IOError:
# raise RuntimeError from None
'''定義清理操作'''
# try:
# raise KeyboardInterrupt
# finally:
# print('Goodbye, world!')
'''一個更為復雜的例子'''
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
print(divide(2,1))
第十部分:類
"""
作者:川川
時間:2021/7/27
"""
# class Complex:
# def __init__(self, realpart, imagpart):
# self.r = realpart
# self.i = imagpart
# x = Complex(3.0, -4.5)
# print(x.r,x.i)
'''實體物件?'''
# x.counter = 1
# while x.counter < 10:
# x.counter = x.counter * 2
# print(x.counter)
# del x.counter
'''9.3.4. 方法物件'''
''''通常,方法在系結后立即被呼叫'''
# class MyClass:
# """A simple example class"""
# i = 12345
#
# def f(self):
# return 'hello world'
# x=MyClass()
# xf = x.f
# while True:
# print(xf())
'''9.3.5. 類和實體變數'''
# class Dog:
# kind = 'canine'
# def __init__(self, name):
# self.name = name
# d = Dog('Fido')
# e = Dog('Buddy')
# print(d.name)
# print(e.name)
# print(d.kind)
''''正確的類設計應該使用實體變數:'''
# class Dog:
# def __init__(self, name):
# self.name = name
# self.tricks = [] # creates a new empty list for each dog
#
# def add_trick(self, trick):
# self.tricks.append(trick)
# d = Dog('Fido')
# e = Dog('Buddy')
# d.add_trick('roll over')
# e.add_trick('play dead')
# e.add_trick('play dead')
# # print(d.tricks)
# print(e.tricks)
''''迭代器'''
# for element in [1, 2, 3]:
# print(element)
# for element in (1, 2, 3):
# print(element)
# for key in {'one':1, 'two':2}:
# print(key)
# for char in "123":
# print(char)
# for line in open("workfile"):
# print(line, end='')
'''生成器'''
# def reverse(data):
# for index in range(len(data)-1, -1, -1):
# yield data[index]
#
# for char in reverse('golf'):
# print(char)
'''生成器運算式'''
# a=sum(i*i for i in range(10))
# print(a)
# xvec = [10, 20, 30]
# yvec = [7, 5, 3]
# c=sum(x*y for x,y in zip(xvec, yvec))
# print(c)
第十一部分:標準庫簡介
"""
作者:川川
時間:2021/7/27
"""
'''作業系統介面(個人感覺沒啥用)'''
# import os
# print(os.getcwd())#列印出當前檔案位置
# os.chdir('/server/accesslogs')#改變運行位置
# os.system('mkdir today') #運行這個再系統shell
'''檔案通配符'''
'''glob 模塊提供了一個在目錄中使用通配符搜索創建檔案串列的函式:'''
# import glob
# print(glob.glob('*.py'))
'''命令列引數'''
# import sys
# print(sys.argv)#列印本檔案位置
''' 字串模式匹配'''
# import re
# b=re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
# print(b)
# a='tea for too'.replace('too', 'two')
# print(a)
'''數學'''
# import math
# a=math.cos(math.pi / 4)
# print(a)
# import random
# b=random.choice(['apple', 'pear', 'banana'])
# print(b)
'''互聯網訪問'''
# from urllib.request import urlopen
# with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
# for line in response:
# line = line.decode('utf-8') # Decoding the binary data to text.
# if 'EST' in line or 'EDT' in line:
# print(line)
# smtplib 用于發送郵件
# import smtplib
# server = smtplib.SMTP('localhost')
# server.sendmail('soothsayer@example.org', 'jcaesar@example.org')
# server.quit()
''' 日期和時間'''
# from datetime import date
# now = date.today()
# print(now)
# a=now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
# print(a)
# birthday = date(2000, 9, 20)
# age = now - birthday
# c=age.days
# print(c)
'''資料壓縮'''
# import zlib
# s = b'witch which has which witches wrist watch'
# print(len(s))
# t = zlib.compress(s)
# print(len(t))
# print( zlib.decompress(t))
# print(zlib.crc32(s))
'''性能測量'''
# from timeit import Timer
# a= Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
# print(a)
第十二部分:協程
"""
作者:川川
時間:2021/7/27
"""
# import asyncio
# async def main():
# print('Hello ...')
# await asyncio.sleep(1)
# print('... World!')
# asyncio.run(main())
'''等待 1 秒后列印 "hello",然后 再次 等待 2 秒后列印 "world"'''
# import asyncio
# import time
#
# async def say_after(delay, what):
# await asyncio.sleep(delay)
# print(what)
# async def main():
# print(f"started at {time.strftime('%X')}")
# await say_after(1, 'hello')
# await say_after(2, 'world')
# print(f"finished at {time.strftime('%X')}")
# asyncio.run(main())
'''asyncio.create_task() 函式用來并發運行作為 asyncio 任務 的多個協程,'''
# async def main():
# task1 = asyncio.create_task(
# say_after(1, 'hello'))
# task2 = asyncio.create_task(
# say_after(2, 'world'))
# print(f"started at {time.strftime('%X')}")
# # Wait until both tasks are completed (should take
# # around 2 seconds.)
# await task1
# await task2
#
# print(f"finished at {time.strftime('%X')}")
# asyncio.run(main())
'''Python 協程屬于 可等待 物件,因此可以在其他協程中被等待'''
# import asyncio
#
# async def nested():
# return 42
#
# async def main():
# # Nothing happens if we just call "nested()".
# # A coroutine object is created but not awaited,
# # so it *won't run at all*.
# # Let's do it differently now and await it:
# print(await nested()) # will print "42".
#
# asyncio.run(main())
'''
協程函式: 定義形式為 async def 的函式;
協程物件: 呼叫 協程函式 所回傳的物件,
'''
'''當一個協程通過 asyncio.create_task() 等函式被封裝為一個 任務,該協程會被自動調度執行'''
# import asyncio
#
# async def nested():
# return 42
#
# async def main():
# # Schedule nested() to run soon concurrently
# # with "main()".
# task = asyncio.create_task(nested())
#
# # "task" can now be used to cancel "nested()", or
# # can simply be awaited to wait until it is complete:
# await task
# asyncio.run(main())
'''運行 asyncio 程式'''
'''asyncio.run(coro, *, debug=False)?'''
# import asyncio
# async def main():
# await asyncio.sleep(1)
# print('hello')
#
# asyncio.run(main())
'''創建任務'''
'''asyncio.create_task(coro, *, name=None)?'''
# import asyncio
# async def coro():
# return 2021
# task = asyncio.create_task(coro())#python3.7+
# This works in all Python versions but is less readable
# task = asyncio.ensure_future(coro())#before python3.7
'''休眠'''
''' asyncio.sleep(delay, result=None, *, loop=None)?'''
'''以下協程示例運行 5 秒,每秒顯示一次當前日期'''
# import asyncio
# import datetime
#
# async def display_date():
# loop = asyncio.get_running_loop()
# end_time = loop.time() + 5.0
# while True:
# print(datetime.datetime.now())
# if (loop.time() + 1.0) >= end_time:
# break
# await asyncio.sleep(1)
#
# asyncio.run(display_date())
'''并發運行任務'''
''' asyncio.gather(*aws, loop=None, return_exceptions=False)?'''
# import asyncio
#
# async def factorial(name, number):
# f = 1
# for i in range(2, number + 1):
# print(f"Task {name}: Compute factorial({i})...")
# await asyncio.sleep(1)
# f *= i
# print(f"Task {name}: factorial({number}) = {f}")
#
# async def main():
# # Schedule three calls *concurrently*:
# await asyncio.gather(
# factorial("A", 2),
# factorial("B", 3),
# factorial("C", 4),
# )
#
# asyncio.run(main())
'''屏蔽取消操作'''
'''asyncio.shield(aw, *, loop=None)保護一個 可等待物件 防止其被 取消'''
# res = await shield(something())#demo
'''如果希望完全忽略取消操作 (不推薦) 則 shield() 函式需要配合一個 try/except 代碼段'''
# try:
# res = await shield(something())
# except CancelledError:
# res = None
'''超時'''
'''asyncio.wait_for(aw, timeout, *, loop=None)?'''
# import asyncio
# async def eternity():
# # Sleep for one hour
# await asyncio.sleep(3600)
# print('yay!')
#
# async def main():
# # Wait for at most 1 second
# try:
# await asyncio.wait_for(eternity(), timeout=1.0)
# except asyncio.TimeoutError:
# print('timeout!')
#
# asyncio.run(main())
'''簡單等待'''
'''syncio.wait(aws, *, loop=None, timeout=None, return_when=ALL_COMPLETED)'''
# 用法:
# import asyncio
# done, pending = await asyncio.wait(aws)
# async def foo():
# return 42
#
# task = asyncio.create_task(foo())
# done, pending = await asyncio.wait({task})
#
# if task in done:
# asyncio.run(task)
# # Everything will work as expected now.
'''在執行緒中運行'''
'''asyncio.to_thread(func, /, *args, **kwargs)在不同的執行緒中異步地運行函式 func,'''
'''這個協程函式主要是用于執行在其他情況下會阻塞事件回圈的 IO 密集型函式/方法'''
# import asyncio,time
# def blocking_io():
# print(f"start blocking_io at {time.strftime('%X')}")
# # Note that time.sleep() can be replaced with any blocking
# # IO-bound operation, such as file operations.
# time.sleep(1)
# print(f"blocking_io complete at {time.strftime('%X')}")
#
# async def main():
# print(f"started main at {time.strftime('%X')}")
#
# await asyncio.gather(
# asyncio.to_thread(blocking_io),
# asyncio.sleep(1))
# print(f"finished main at {time.strftime('%X')}")
# asyncio.run(main())
''':要取消一個正在運行的 Task 物件可使用 cancel() 方法,呼叫此方法將使該 Task 物件拋出一個 CancelledError 例外給打包的協程'''
'''以下示例演示了協程是如何偵聽取消請求的'''
# import asyncio
# async def cancel_me():
# print('cancel_me(): before sleep')
#
# try:
# # Wait for 1 hour
# await asyncio.sleep(3600)
# except asyncio.CancelledError:
# print('cancel_me(): cancel sleep')
# raise
# finally:
# print('cancel_me(): after sleep')
#
# async def main():
# # Create a "cancel_me" Task
# task = asyncio.create_task(cancel_me())
#
# # Wait for 1 second
# await asyncio.sleep(1)
#
# task.cancel()
# try:
# await task
# except asyncio.CancelledError:
# print("main(): cancel_me is cancelled now")
#
# asyncio.run(main())
'''基于生成器的協程'''
'''@asyncio.coroutine
用來標記基于生成器的協程的裝飾器,
此裝飾器使得舊式的基于生成器的協程能與 async/await 代碼相兼容
'''
# import asyncio
# @asyncio.coroutine
# def old_style_coroutine():
# yield from asyncio.sleep(1)
#
# async def main():
# await old_style_coroutine()
'''佇列能被用于多個的并發任務的作業量分配:'''
import asyncio
import random
import time
async def worker(name, queue):
while True:
# Get a "work item" out of the queue.
sleep_for = await queue.get()
# Sleep for the "sleep_for" seconds.
await asyncio.sleep(sleep_for)
# Notify the queue that the "work item" has been processed.
queue.task_done()
print(f'{name} has slept for {sleep_for:.2f} seconds')
async def main():
# Create a queue that we will use to store our "workload".
queue = asyncio.Queue()
# Generate random timings and put them into the queue.
total_sleep_time = 0
for _ in range(20):
sleep_for = random.uniform(0.05, 1.0)
total_sleep_time += sleep_for
queue.put_nowait(sleep_for)
# Create three worker tasks to process the queue concurrently.
tasks = []
for i in range(3):
task = asyncio.create_task(worker(f'worker-{i}', queue))
tasks.append(task)
# Wait until the queue is fully processed.
started_at = time.monotonic()
await queue.join()
total_slept_for = time.monotonic() - started_at
# Cancel our worker tasks.
for task in tasks:
task.cancel()
# Wait until all worker tasks are cancelled.
await asyncio.gather(*tasks, return_exceptions=True)
print('====')
print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')
print(f'total expected sleep time: {total_sleep_time:.2f} seconds')
asyncio.run(main())
如果你有一定的編程基礎,那么你一定會通過本文章查漏補缺,同時領略python基礎,由于內容實在過多,本篇文章偏語法介紹,并沒有舉很多例子,如有不好之處多對見諒,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/290664.html
標籤:python
