一. 準(zhǔn)備知識(shí)
1. python 安裝
安裝完成后倔既,在cmd 中輸入
- python ,查看版本;
- exit() :退出
2. 開(kāi)發(fā)工具 --- pycharm
- 控制臺(tái)運(yùn)行程序 <Terminal>:
(venv) C:\develop\python_3_8_2\Code\test>python Chapter_1\hello.py
3. python 程序是如何運(yùn)行的遣妥?
源代碼 ----》 解釋器 ---》 010101(機(jī)器碼)
.pyc 文件 CPython / JPython /PYPY 三種
二. 變量
1. 注釋
- 單行 : #
- 多行 : """ / '''
2. 變量
變量 : 內(nèi)存的別名
3. 變量類(lèi)型
- 變量類(lèi)型 : type()
- isinstance() : 來(lái)判斷一個(gè)對(duì)象是否是一個(gè)已知的類(lèi)型坤检,類(lèi)似 type()。
isinstance() 與 type() 區(qū)別:
- type() 不會(huì)認(rèn)為子類(lèi)是一種父類(lèi)類(lèi)型鞭衩,不考慮繼承關(guān)系门驾。
- isinstance() 會(huì)認(rèn)為子類(lèi)是一種父類(lèi)類(lèi)型射赛,考慮繼承關(guān)系。
- 如果要判斷兩個(gè)類(lèi)型是否相同推薦使用 isinstance()奶是。
4. 關(guān)鍵字
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>>
5. 輸入
input()
6. 輸出
print(*objects, sep='', end='\n', file=sys.stdout, flush=False)
- objects 楣责, 輸出的對(duì)象;
- sep聂沙, 分隔符(默認(rèn)為空字符串)腐魂;
- end, 結(jié)束符(默認(rèn)為換行符逐纬,默認(rèn)換一行)蛔屹;
- file, 輸出流豁生;
- flush兔毒, 是否強(qiáng)制刷新輸出流(默認(rèn)情況下不會(huì)輕質(zhì)輸出);
#file
file_source = open('zen.txt', 'a+', encoding='utf-8')
print('人生苦短甸箱,我用python', file=file_source)
file_source.close()
7. 運(yùn)算符
** 冪 - 返回x的y次冪
// 取整除 - 返回商的整數(shù)部分(向下取整)
a%b ---> r=a-b*(a//b)
# 交換兩個(gè)數(shù)
a, b = 5, 10
a, b = b, a
print(a, b)
邏輯運(yùn)算符
and / or / nor
運(yùn)算符 | 邏輯表達(dá)式 | 描述實(shí)例 |
---|---|---|
and | x and y | 如果 x 為 False育叁,x and y 返回 False,否則它返回 y 的計(jì)算值芍殖。 |
or | x or y | 如果 x 是非 0豪嗽,它返回 x 的值,否則它返回 y 的計(jì)算值。 |
not | not x | 如果 x 為 True龟梦,返回 False 隐锭。如果 x 為 False,它返回 True计贰。 |
三. 流程控制
1. if
2. if-elif-else
3. 三元運(yùn)算符
x = -1
y = x if x >= 0 else -x
print(y)
4. 省略表達(dá)式
5. while() 循環(huán)
6. for() 循環(huán)
range() : range (start, stop [, step])
- start
- stop
- step : 步長(zhǎng)
range(5) ===> range(0, 5) : [ 0, 5)
7. 循環(huán)跳出語(yǔ)句 break
8. 循環(huán)跳出語(yǔ)句continue : 跳出本次循環(huán)
9. 循環(huán)else子句
- while -else
- for - else
else 子句钦睡, 循環(huán)正常離開(kāi)時(shí),執(zhí)行的語(yǔ)句
for else語(yǔ)句可以總結(jié)成以下話躁倒。
如果我依次做完了所有的事情(for正常結(jié)束)荞怒,我就去做其他事(執(zhí)行else),若做到一半就停下來(lái)不做了(中途遇到break)秧秉,我就不去做其他事了(不執(zhí)行else)褐桌。
英文原文
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there is no next item.中文譯文
用 break 關(guān)鍵字終止當(dāng)前循環(huán)就不會(huì)執(zhí)行當(dāng)前的 else 語(yǔ)句,而使用 continue 關(guān)鍵字快速進(jìn)入下一論循環(huán)象迎,或者沒(méi)有使用其他關(guān)鍵字撩嚼,循環(huán)的正常結(jié)束后,就會(huì)觸發(fā) else 語(yǔ)句挖帘。
與continue 語(yǔ)句沒(méi)有關(guān)系
str = "hello world"
for item in str:
if item == "l":
break
print(item)
else:
print("打印完成")
四. 字符串
1. 字符串基礎(chǔ)
單引號(hào) / 雙引號(hào) / 三個(gè)單引號(hào)或三個(gè)雙引號(hào)。
2. 索引
3. 切片
motto = "abcd,efg"
motto[0:2]
motto[1:]
motto[0:10:2]
motto[-5:-1] # 從小到大
- 切片區(qū)間從小到大
- 切片區(qū)間左開(kāi)右閉
- 索引越界會(huì)報(bào)錯(cuò)
- 切片越界會(huì)自動(dòng)處理
4. 字符串是不可變類(lèi)型
- mutable 可變類(lèi)型
- immmutable 不可變類(lèi)型
5. 字符串常用方法 --- 內(nèi)置方法
- dir() 函數(shù)
不帶參數(shù)時(shí)恋技,返回當(dāng)前范圍內(nèi)的變量拇舀、方法和定義的類(lèi)型列表。
6. 字符串拼接方法 --- join() 函數(shù)
sep.join(iterable)
以 sep 作為分隔符蜻底,將 iterable 中所有的元素 合并為一個(gè)新的字符串骄崩。 iteratable 可以是一個(gè)數(shù)組 / 元組等。
list_var = ['www', 'baidu', 'com']
str_var = '.'.join(list_var )
7. 大小寫(xiě)轉(zhuǎn)換
- upper()
- lower()
- title() :所有單詞都已大寫(xiě)開(kāi)始薄辅,其余均為小寫(xiě)要拂;
- capitalize : 將字符串的第一個(gè)字符串轉(zhuǎn)換為大寫(xiě); ( 把…首字母大寫(xiě))
- swapcase : 大寫(xiě)的字母轉(zhuǎn)換為小寫(xiě)站楚, 小寫(xiě)轉(zhuǎn)為大寫(xiě)脱惰。
8. 5種字符串的檢索方法
count() : 統(tǒng)計(jì)字符串里指定字符出現(xiàn)的次數(shù); 區(qū)分大小寫(xiě)窿春。
find() :
查找某字符串里是否 包含 被查詢的子字符串拉一;
如果找到,返回子串的索引旧乞,否則返回-1蔚润。index() : 沒(méi)有找到時(shí),拋出異常尺栖。
startwith() : 查尋 字符串是否是以 指定子字符串開(kāi)頭 嫡纠。 找到了返回True,否則返回False。
endwith()
9. 3種字符串的修剪方法: strip / lstrip/ rstrip
- strip() : 移除字符串頭尾的字符(默認(rèn)為空格 或 換行符)除盏,不移除中間的字符串叉橱。
- lstrip()
- rstrip()
10. 字符串格式化
str = "the length of (%s) is %d" %('runoob',len('runoob'))
print(str)
- % --- formatting : 用元組替換。
- str.format() : 通過(guò){} 和 : 來(lái)替換以前的%痴颊。 可以接受不限個(gè)參數(shù)赏迟,位置可以不按順序。
- f-sring : f或F修飾符引領(lǐng)的字符串(f'xxx 或 F'xxx), 以大括號(hào){}標(biāo)明被替換的字段
#你好Allen蠢棱,這是你登錄的第3次, 本次消費(fèi)99.5員
str = '你好{0}锌杀,這是你登錄的第{1}次, 本次消費(fèi){2:.1f}員'.format('Allen', 3, 99.47)
print(str)
str1 = '你好{name},這是你登錄的第{time}次, 本次消費(fèi){count:.1f}元'.format(name=name, time=logInTime, count=count)
str2 = F'你好{name}泻仙,這是你登錄的第{logInTime}次, 本次消費(fèi){count:.1f}元'
5.14 f-sring
- 表發(fā)生求值 與 函數(shù)調(diào)用
- 引號(hào) / 大括號(hào) 和 反斜杠 : 大括號(hào)內(nèi)糕再,不能使用轉(zhuǎn)移符號(hào) / 外邊可以
5.15 f-string 自定義格式 : 對(duì)齊 / 寬度 / 符號(hào) / 補(bǔ)零 / 精度 / 進(jìn)制等
- 對(duì)齊 : < 左對(duì)齊 / > 右對(duì)齊 / ^ 居中
s = 3.1415926
num = f'{s:<13}' # 占13位,左對(duì)齊
print(num) '3.1415926 '
數(shù)字符號(hào)相關(guān)格式 : + :負(fù)數(shù)前 加(-)玉转,正數(shù)前加(+)突想;(空格),負(fù)數(shù)前加(-)究抓,正數(shù)前加(空格)猾担; - ,負(fù)數(shù)前 加(-)刺下,正數(shù)前不加任何符號(hào)绑嘹。
數(shù)字顯示(進(jìn)制)
#0b #0o
print(f'{123:#0x}') #0x7b
- 寬度與精度 :
width : 整數(shù) width指定快讀;
0width : 開(kāi)頭的0橘茉,指定高位用0補(bǔ)足寬度工腋;
width.precision : precision 顯示精度;
a=123.456
print(f'{a:8.2f}') #' 123.46'
print(f'{a:08.2f}') #'00123.46'
s="hello"
print(f'{s:8.3s}') #'hel ' 長(zhǎng)度是8位畅卓,我只取3位擅腰。
- 千分位分隔符 : , 或 _
其中 10進(jìn)制翁潘,每 3個(gè)數(shù)分隔趁冈;
其余進(jìn)制數(shù),每4個(gè)數(shù)分隔拜马;
b=1234567890.1234567
print(f'{b:_f}')
- 格式類(lèi)型相關(guān)描述符
%Y %M %D
五. python list / tuple /dict / set
1. list
- append : 末尾追加箱歧;
- insert : 指定位置插入;
list_a = ['aa', 'bb', 'cc']
list_a.insert(2, 'ff')
print(list_a) # ['aa', 'bb', 'ff', 'cc']
- pop() : 默認(rèn)刪除末尾元素一膨, pop(1) 刪除指定位置元素
2. tuple 元組
- 不可更改 : 賦值時(shí)呀邢,決定了所有的元素
# 聲明
tuple_b = ('aa', 'bb', 'cc')
- len(list_b)
3. dict 字典 : 鍵值對(duì), map
- 查找速度快豹绪;
- 利用空間換時(shí)間价淌。
dict_b ={'s':"Allen", 2:"bob", 3:"lucy"}
print(dict_b['s']) #Allen
print(2 in dict_b) #True
print(dict_b.get('s')) #Allen
print(dict_b.items()) #dict_items([('s', 'Allen'), (2, 'bob'), (3, 'lucy')])
- dict.get(key, default=None) 返回指定鍵的值申眼,如果值不在字典中返回default值.
4. set
- 集合(set)是一個(gè)無(wú)序的不重復(fù)元素序列。 可視作:沒(méi)有value的字典蝉衣。
- 可以使用大括號(hào) { } 或者 set() 函數(shù)創(chuàng)建集合括尸,注意:創(chuàng)建一個(gè)空集合必須用 set() 而不是 { },因?yàn)?{ } 是用來(lái)創(chuàng)建一個(gè)空字典病毡。
- 一般用作去重或集合求并求交濒翻。
#創(chuàng)建格式:
parame = {value01,value02,...}
#或者
set(value)
- 集合 求交 &, 并集 |
- 增加元素add
- 刪除 remove
- 當(dāng)集合是由列表和元組組成時(shí),set.pop()是從左邊刪除元素啦膜。(集合 對(duì)list 或者tuple 升序)
六. 函數(shù)
1. 基本用法
def functionname( parameters ):
"函數(shù)_文檔字符串"
function_suite
return [expression]
---
def printme( str ):
"打印傳入的字符串到標(biāo)準(zhǔn)顯示設(shè)備上"
print str
return
---
#默認(rèn)參數(shù)
def printme( str="hello" ):
---
#不定長(zhǎng)參數(shù)
def print_args(s, *args):
print(s,end=' ')
for a in args:
print(a, end=' ')
return
# print_args('hello')
print_args('aaaa', 'a', 1 ,'b') # aaaa a 1 b
---
# 參數(shù)次序可以變
def print_two(a, b):
print(a,b)
print_two(b='bb', a='aa') # aa bb
2. 內(nèi)嵌和閉包
- 內(nèi)嵌函數(shù):函數(shù)里又嵌套一個(gè)函數(shù)
def fun1():
print('fun1()在被調(diào)用')
def fun2():
print('fun2()在被調(diào)用')
fun2()
閉包:閉包是函數(shù)里面嵌套函數(shù)有送,外層函數(shù)返回里層函數(shù),這種情況稱(chēng)之為閉包.
閉包是概念僧家,不是某種函數(shù)類(lèi)型雀摘,和遞歸的概念類(lèi)似,就是種特殊的函數(shù)調(diào)用八拱;
閉包可以得到外層函數(shù)的局部變量阵赠,是函數(shù)內(nèi)部和函數(shù)外部溝通的橋梁。global關(guān)鍵字修飾變量后標(biāo)識(shí)該變量是全局變量肌稻,對(duì)該變量進(jìn)行修改就是修改全局變量清蚀;
nonlocal關(guān)鍵字修飾變量后標(biāo)識(shí)該變量是上一級(jí)函數(shù)中的局部變量,如果上一級(jí)函數(shù)中不存在該局部變量爹谭,nonlocal位置會(huì)發(fā)生錯(cuò)誤(最上層的函數(shù)使用nonlocal修飾變量必定會(huì)報(bào)錯(cuò))枷邪。
3. lamba表達(dá)式 : 匿名表達(dá)式
# 可寫(xiě)函數(shù)說(shuō)明
sum = lambda arg1, arg2: arg1 + arg2
# 調(diào)用sum函數(shù)
print "相加后的值為 : ", sum( 10, 20 )
print "相加后的值為 : ", sum( 20, 20 )
七. 模塊
1. import
在同一文件下的文件,可以直接import旦棉;
# hello.py
def print_hello():
print("hello")
return
#main.py
import hello
hello.print_hello()
2. from...import
這個(gè)聲明不會(huì)把整個(gè) fib 模塊導(dǎo)入到當(dāng)前的命名空間中,它只會(huì)將 fib 里的 fibonacci 單個(gè)引入到執(zhí)行這個(gè)聲明的模塊的全局符號(hào)表药薯。
# hello.py
def print_hello():
print("hello")
return
#main.py
from hello import print_hello
print_hello()
3. 不在一個(gè)路徑下
import sys
sys.path.append
import sys
sys.path.append('C:\\develop\\python_3_8_2\\Code\\test\\Chapter_1\\hello')
from hello import print_hello
print_hello()
4. 包 : 一個(gè)目錄及子目錄組成一個(gè)包(可以看作一個(gè)庫(kù))绑洛。
if __name__ == '__main__'
- 新建一個(gè)文件夾;
- 文件夾下童本,新建一個(gè) init.py文件真屯。可以為空穷娱。
import sys
sys.path.append('C:\\develop\\python_3_8_2\\Code\\test\\Chapter_1\\hello\\package_test')
import package_test.hello as hl
hl.print_hello()
5. 標(biāo)準(zhǔn)庫(kù)
八. 類(lèi)
1. 類(lèi)基本定義
# 類(lèi)定義
class Human(object):
pass
# 類(lèi)屬性 : 這個(gè)屬性和類(lèi)綁定绑蔫, 并不是和實(shí)例綁定
class Human(object):
taisheng = True # 胎生
# 實(shí)例屬性 : 這個(gè)name是和實(shí)例綁定的
class Human(object):
def __init__(self, name): # 構(gòu)造函數(shù)
self.name = name
human_a = Human("Allen")
# 類(lèi)方法
class Human(object):
def __init__(self, name): # 構(gòu)造函數(shù)
self.name = name
def walk(self):
print(self.name + " is walking")
human_a = Human("Allen")
human_a.walk() # Allen is walking
- 訪問(wèn)控制 : 如果不想外部直接訪問(wèn),則在屬性前面加__name(_name protected)泵额。這樣外部就無(wú)法訪問(wèn)配深,如果還想訪問(wèn),則get方法嫁盲。
2. 繼承
3. 方法繼承
class Parent: # 定義父類(lèi)
def myMethod(self):
print ('調(diào)用父類(lèi)方法')
class Child(Parent): # 定義子類(lèi)
def myMethod(self):
print ('調(diào)用子類(lèi)方法')
c = Child() # 子類(lèi)實(shí)例
c.myMethod() # 子類(lèi)調(diào)用重寫(xiě)方法
super(Child,c).myMethod() #用子類(lèi)對(duì)象調(diào)用父類(lèi)已被覆蓋的方法
九. python 文件讀寫(xiě)
open(file, mode='r')
[file.readline([size])] # 讀取整行篓叶,包括 "\n" 字符, 字節(jié)數(shù);
# 寫(xiě)
f = open("zen.txt", 'a+')
content = f.read()
f.write('hhh')
f.close()
f = open("zen.txt", 'a+')
content = f.read()
f.writelines(['hhh', 'lll'])
f.close()
十. python 異常
1. try ... except
try:
f = open("111qwqw111.txt", 'r')
except OSError:
print('文件出錯(cuò)T_T')
try:
f = open("111qwqw111.txt", 'r')
except OSError as err:
print('錯(cuò)誤的原因是:' + str(err)) #錯(cuò)誤的原因是:[Errno 2] No such file or directory: '111qwqw111.txt'
2. try - finally
finally : 無(wú)論如何都會(huì)被執(zhí)行的代碼缸托。
try:
正常的操作
......................
except:
發(fā)生異常左敌,執(zhí)行這塊代碼
......................
else:
如果沒(méi)有異常執(zhí)行這塊代碼
3. raise 語(yǔ)句 : 引發(fā)一個(gè)異常
raise AAAA("除數(shù)為零的異常")
raise NameError("qq", 1111)
十一. 迭代器 和 生成器
1. 迭代器
for each in list
iter()
next()
_iter_() 方法返回一個(gè)特殊的迭代器對(duì)象, 這個(gè)迭代器對(duì)象實(shí)現(xiàn)了 _next_() 方法并通過(guò) StopIteration 異常標(biāo)識(shí)迭代的完成俐镐。
_next_() 方法會(huì)返回下一個(gè)迭代器對(duì)象矫限。
it = iter("hello")
print(next(it))
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter)) #1
print(next(myiter)) #2
print(next(myiter)) #3
print(next(myiter)) #4
print(next(myiter)) #5
2. 生成器 yield
中斷
def myGen():
print("生成器被執(zhí)行")
yield 1
yield 2
myG = myGen()
print(next(myG)) # 1
print(next(myG)) # 2
十二. 圖形用戶界面: EasyGui
- 安裝完之后, 安裝文件在 : C:\develop\python_3_8_2\Lib\site-packages\easygui.py
# 參考文檔 https://blog.csdn.net/qiaoermeng/article/details/99718378
#from easygui import *
import easygui as g
import sys
while 1:
g.msgbox("嗨佩抹,歡迎進(jìn)入第一個(gè)界面小游戲^_^")
msg = "請(qǐng)問(wèn)你希望在魚(yú)C工作室學(xué)習(xí)到什么知識(shí)呢叼风?"
title = "小游戲互動(dòng)"
choices = ["談戀愛(ài)", "編程", "OOXX", "琴棋書(shū)畫(huà)"]
choice = g.choicebox(msg, title, choices)
# note that we convert choice to string, in case
# the user cancelled the choice, and we got None.
g.msgbox("你的選擇是: " + str(choice), "結(jié)果")
msg = "你希望重新開(kāi)始小游戲嗎?"
title = "請(qǐng)選擇"
if g.ccbox(msg, title): # show a Continue/Cancel dialog
pass # user chose Continue
else:
sys.exit(0) # user chose Cancel