1. 程式人生 > >Python3 基礎(itcast學習筆記)

Python3 基礎(itcast學習筆記)

1.Python變數的型別

這裡寫圖片描述

用type(變數的名字)來檢視變數的型別

#!/usr/bin/python3 
a = 10
b = 10.0
c = True
# ./test.py 
<class 'int'> <class 'float'> <class 'bool'>

2.格式化符號

在程式中%這樣的符號是python的格式化輸出

#!/usr/bin/python3 
age = 18
name = "Tom"
print("My name is %s and I am %d years old"%(name,age))
# ./test.py 
My name is Tom and I am 18 years old

在輸出的時候如果有\n,則\n後的內容將換行輸出
練習:完成以下名片的列印
這裡寫圖片描述

#!/usr/bin/python3 
name = input("please input your name")
qq = input("please input your qq number")
tel = int(input("please input your telephone num"))
address = input("please input your company address")
print("==================================="
) print("name:%s"%name) print("QQ:%s"%qq) print("telephone:%d"%tel) print("address:%s"%address) print("===================================") # ./test.py please input your nameDaemon please input your qq number156841028 please input your telephone num12659874562 please input your company addresstianfupark =================================== name:Daemon QQ:156841028
telephone:12659874562 address:tianfupark ===================================

知識點:input() 它接受表示式輸入,並把表示式的結果給等號左邊的變數

3.運算子

1)算術運算子
這裡寫圖片描述

>>> a = 10
>>> b = 20
>>> a+b
30
>>> a-b
-10
>>> a*b
200
>>> a/b
0.5
>>> a//b
0
>>> a%b
10
>>> a**b
100000000000000000000

2)賦值運算子 =
=號右邊的結果給左邊的變數賦值

>>> a,b = 10,20
>>> a
10
>>> b
20

3)複合賦值運算子
這裡寫圖片描述
4)比較(關係)運算子
這裡寫圖片描述
5)邏輯運算子
這裡寫圖片描述
6)常用的資料型別轉換
這裡寫圖片描述

4.判斷語句

1)if判斷語句
if 要判斷的條件:
條件成立時,要做的事情

#!/usr/bin/python3 
age = int(input("please input your age:"))
if age >= 18:
    print("You can play games")
# ./test.py 
please input your age:18
You can play games
# ./test.py 
please input your age:17

2)if - else
if 條件:
滿足條件時要做的事情1
滿足條件時要做的事情2
滿足條件時要做的事情3
else:
不滿足條件時要做的事情1
不滿足條件時要做的事情2
不滿足條件時要做的事情3

#!/usr/bin/python3 
age = int(input("please input your age:"))
if age >= 18:
    print("You can play games")
else:
    print("You are so young do homework")
# ./test.py 
please input your age:19
You can play games
# ./test.py 
please input your age:10
You are so young do homework

3)elif
if xxx1:
做事情1
elif xxx2:
做事情2
elif xxx3:
做事情3

#!/usr/bin/python3 
score = int(input("please input your score:"))
if score>=90 and score <= 100:
    print("Your level is A")
elif score>=80 and score <90:
    print("Your level is B")
elif score>=70 and score <80:
    print("Your level is C")
elif score>=60 and score <70:
    print("Your level is D")
else: 
    print("Your level is E")
# ./test.py 
please input your score:100
Your level is A
# ./test.py 
please input your score:60
Your level is D
# ./test.py 
please input your score:40
Your level is E

練習:猜拳遊戲

#!/usr/bin/python3 
import random
player = int(input("please input:剪刀(0) 石頭(1) 布(2)"))
computer = random.randint(0,2)

if(((player==0)and(computer==2)) or ((player==1)and(computer==0)) or
((player==2)and(computer==1)) ):
    print("You Win, You'are so Good!")
elif player==computer:
    print("equal ,again...")
else:
    print("You lose,come on...")
# ./test.py 
please input:剪刀(0) 石頭(1) 布(2)0
You Win, You'are so Good!
# ./test.py 
please input:剪刀(0) 石頭(1) 布(2)0
You Win, You'are so Good!
# ./test.py 
please input:剪刀(0) 石頭(1) 布(2)0
You lose,come on...
# ./test.py 
please input:剪刀(0) 石頭(1) 布(2)0
You lose,come on...

需要多次重複執行的程式碼可以用迴圈來完成
1)while迴圈
while 條件:
條件滿足時,做的事情1
條件滿足時,做的事情2

#!/usr/bin/python3 
i = 0
while i < 5:
    print("i=%d"%i)
    i+=1
# ./test.py 
i=0
i=1
i=2
i=3
i=4

計算1到100的累積和

#!/usr/bin/python3 
i = 0
sum = 0
while i <= 100:
    sum += i
    i+=1
# ./test.py 
the sum of 1 from 100 is:5050

while巢狀:9*9表

#!/usr/bin/python3 
i=1
while i<=9:
    j = 1
    while j<=i:
        print("%d*%d=%d "%(i,j,i*j),end="")
        j+=1
    print("\n")
    i+=1
# ./test.py 
1*1=1 

2*1=2 2*2=4 

3*1=3 3*2=6 3*3=9 

4*1=4 4*2=8 4*3=12 4*4=16 

5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 

6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 

7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 

8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 

9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 

2) for 迴圈
for迴圈可以遍歷任何序列的專案,如一個列表或者一個字串
for 臨時變數 in 列表或者字串:
迴圈滿足條件時執行
else:
迴圈不滿足條件時執行

#!/usr/bin/python3 

name = "DangGo"

for x in name:
    print(x)
# ./test.py 
D
a
n
g
G
o

break:用來結束整個迴圈
continue:用來結束本次迴圈,緊接著執行下一次的迴圈
注意:break/continue只能用在迴圈中,不能單獨使用
break/continue在巢狀迴圈中,只對最近的一層迴圈起作用

4.字串

雙引號或者單引號中的資料,就是字串
1)下標索引
字串實際上就是字元的陣列,支援下標索引
如果想取出部分字元,可以通過下標的方法,python中下標從0開始

name = "DangGo"
print(name[0])
print(name[1])
print(name[2])
print(name[3])
# ./test.py 
D
a
n
g

2)切片
切片是指對操作的物件擷取其中一部分的操作
[起始:結束:步長]
注意:選取的區間屬於左閉右開型,從起始位開始,到結束位的前一位結束,不包結束位本身

name = "DangGo"
print(name[0:3]) #起始0,結束3不包含3
# ./test.py 
Dan  

3)字串常見操作
find:檢測str是否包含在mystr中,如果是返回開始的索引值,否則返回-1

name = "My name is Tom str hao bao hao"
pos = name.find("Tom")
print(pos)
# ./test.py 
11

index:跟find()方法一樣,如果str不在mystr中會報一個異常

name = "My name is Tom str hao bao hao"
pos = name.index("Tomz")
print(pos)
# ./test.py 
Traceback (most recent call last):
  File "./test.py", line 4, in <module>
    pos = name.index("Tomz")
ValueError: substring not found

name = "My name is Tom str hao bao hao"
pos = name.index("Tom")
print(pos)
# ./test.py 
11

count:返回統計在start和end之間str在mystr裡面出現的次數

name = "My name is Tom str Tom hao bao hao"
print(name.count("Tom"))
# ./test.py 
2

replace:把mystr中的str1替換成str2,如果count指定,則替換不超過count次

name = "My name is Tom str Tom hao bao hao"
names = name.replace("Tom","tom")
print(names)
# ./test.py 
My name is tom str tom hao bao hao

5.列表

testList[1, “tom”,12..5]
列表中的元素可以是不同型別的

#!/usr/bin/python3 
testList = [1,2,3,"a",12.5]
for x in testList:
    print(x)
# ./test.py 
1
2
3
a
12.5

列表的相關操作,列表中存放的資料是可以進行修改的,增,刪,改
1)新增元素 增append,extend,insert

>>> A = ["xianwan","xianzhan","xiaohua"]
>>> A
['xianwan', 'xianzhan', 'xiaohua']
>>> A.append("bshui")
>>> A
['xianwan', 'xianzhan', 'xiaohua', 'bshui']

extend : 通過extend可以將另一個集合中的元素新增到列表中

>>> a = [1,2]
>>> b = [3,4]
>>> a.extend(b)
>>> a
[1, 2, 3, 4]

insert(index,object):在指定位置index前插入元素object

>>> a.insert(2,5)
>>> a
[1, 2, 5, 3, 4]

2)修改元素 改
修改元素的時候,要通過下標來確定要修改的是哪個元素,然後才進行修改

>>> a
[1, 2, 5, 3, 4]
>>> a[1] = 6
>>> a
[1, 6, 5, 3, 4]

3)查詢元素in,not in,index,count
查詢:看指定的元素是否存在
in:存在,如果存在那麼結果為true,否則為false
not in:不存在,如果不存在結果為true, 否則為false
index和count與字串用法相同

>>> a
[1, 6, 5, 3, 4]
>>> a.index(5)
2
>>> a.count(5)
1

4)刪除元素del,pop,remove
列表的刪除方法
del:根據下標進行刪除
pop:刪除最後一個元素
remove:根據元素的值進行刪除

>>> a
[1, 3, 5, 7, 9]
>>> del a[0]
>>> a
[3, 5, 7, 9]
>>> a.pop()
9
>>> a
[3, 5, 7]
>>> a.remove(5)
>>> a
[3, 7]

5)排序sort,reverse
sort方法是將list按特定順序重新排列,預設為由小到大,引數reverse=True,可改為倒序,由大到小
reverse方法是將列表逆序

>>> a
[1, 4, 7, 2, 3, 9, 60, 38]
>>> a.sort()
>>> a
[1, 2, 3, 4, 7, 9, 38, 60]
>>> a.reverse()
>>> a
[60, 38, 9, 7, 4, 3, 2, 1]

6.元組

python的元組與列表類似,不同之處元組的元素不能修改,元組使用小括號,列表使用方括號

7.字典

字典和列表一樣,能夠儲存多個數據
字典中找元素時,是根據名字(鍵 名)
字典的每個元素由2部分組成 鍵:值

根據鍵訪問值:
>>> info
{'id': 100, 'name': 'xaoHua', 'sex': 'f'}
>>> info["name"]
'xaoHua'
>>> info["sex"]
'f'

若訪問不存在的鍵會報錯

>>> info["s"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 's'

1)修改元素
字典中的每個元素是可以修改的

>>> info
{'id': 100, 'name': 'xaoHua', 'sex': 'f'}
>>> info["id"] = 101
>>> info
{'id': 101, 'name': 'xaoHua', 'sex': 'f'}

2)新增元素
如果在使用 變數名[“鍵”] = 資料 時,這個鍵在字典中不存在,那麼會新增這個元素

>>> info
{'id': 101, 'name': 'xaoHua', 'sex': 'f'}
>>> info["tel"]=12568836457
>>> info
{'id': 101, 'name': 'xaoHua', 'tel': 12568836457, 'sex': 'f'}

3)刪除元素
對字典進行刪除操作
del 刪除指定元素

>>> info
{'id': 101, 'name': 'xaoHua', 'tel': 12568836457, 'sex': 'f'}
>>> del info["sex"]
>>> info
{'id': 101, 'name': 'xaoHua', 'tel': 12568836457}

del刪除整個字典,刪除後不能訪問

>>> info
{'id': 101, 'name': 'xaoHua', 'tel': 12568836457}
>>> del info
>>> info
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'info' is not defined

clear()只是清空整個字典
4)len() 測量字典中鍵值對的個數

>>> mesg
{'id': 1, 'name': 'beng', 'year': 19}
>>> len(mesg)
3

5)keys 返回一個包含字典所有KEY的列表

>>> mesg
{'id': 1, 'name': 'beng', 'year': 19}
>>> mesg.keys()
dict_keys(['id', 'name', 'year'])

6)values
返回一個包含字典所有value的列表

>>> mesg
{'id': 1, 'name': 'beng', 'year': 19}
>>> mesg.values()
dict_values([1, 'beng', 19])

7)items
返回一個包含所有(鍵,值)元祖的列表

>>> mesg
{'id': 1, 'name': 'beng', 'year': 19}
>>> mesg.items()
dict_items([('id', 1), ('name', 'beng'), ('year', 19)])

遍歷字典的key-value

>>> mesg
{'id': 1, 'name': 'beng', 'year': 19}
>>> for key,value in mesg.items():
...     print("key=%s,value=%s"%(key,value))
... 
key=id,value=1
key=name,value=beng
key=year,value=19

公共方法
這裡寫圖片描述

這裡寫圖片描述

8.引用

在python中,值是靠引用來傳遞的
我們可以用id()來判斷兩個變數是否為同一個值的引用,可以將id值理解為記憶體的地址標示

>>> a = 1
>>> b = a
>>> id(a)
10919424
>>> id(b)
10919424

可變型別:值可以改變:列表list,字典dict
不可變型別:值不可以改變int,long,bool,float,str,tuple

9.函式

把具有獨立功能的程式碼塊組織成為一個小模組,這就是函式
定義函式
def 函式名():
程式碼

>>> def printInfo():
...     print("Life is short, I use Python")
... 
>>> printInfo()
Life is short, I use Python

函式的文件說明:help(函式名)
1)函式引數

>>> def addnum(a,b):
...     return a+b
... 
>>> a = addnum(11,22)
>>> a
33

定義時小括號中的引數,用來接收引數用的,叫形參
呼叫時小括號中的引數,用來傳遞給函式用的,叫實參
在函式中把結果返回給呼叫者,使用return
2)區域性變數
區域性變數:在函式內部定義的變數
不同的函式,可以定義相同的名字的區域性變數,不會產生影響
作用:臨時儲存資料
3)全域性變數
如果一個變數既能在一個函式中使用,也能在其它函式中使用就是全域性變數
總結:在函式外邊定義的變數叫做全域性變數
全域性變數能夠在所有的函式中進行訪問
如果在函式中修改全域性變數,就需要使用global進行宣告
如果全域性變數的名字和區域性變數的名字相同,使用的是區域性變數
4)匿名函式
用lambda建立小型匿名函式,函式語法只包含一個語句

10.檔案操作

1)開啟檔案
在python中,使用open函式可以開啟一個已經存在的檔案,或者建立一個新檔案
open(檔名,訪問模式)
訪問模式
這裡寫圖片描述
2)關閉檔案
close()
3)寫資料write()
4)讀資料read
使用read(num)可以從檔案中讀取資料,num表示要從檔案中讀取的資料的長度,如果沒有num,表示讀取檔案中所有的資料

>>> f = open("test.py","w")
>>> f.write("hello")
5
>>> f.close()
>>> f = open("test.py","r")
>>> f.read()
'hello'
>>> f.close()

5)獲取當前讀寫的位置
f.tell()

>>> f = open("test.py","r")
>>> f.read()
'hello'
>>> f.tell()
5

6)定位到指定位置
如果在讀寫檔案的過程中,需要從另外一個位置進行操作的話,可以使用seek()
seek(offset,from)
offset:偏移量
from:方向 ,0:表示檔案開頭1:表示當前位置2:表示檔案末尾
7)檔案的重新命名
os模組中的rename()可以完成對檔案的重新命名操作
rename(需要修改的檔名,新的檔名)

>>> import os
>>> os.rename("test.py","test1.py")
>>> exit()
root@bshui-virtual-machine:/home/bshui/Python# ls test1.py 
test1.py

8)刪除檔案
remove(要刪除的檔名)

>>> import os
>>> os.remove("test1.py")
>>> exit()
root@bshui-virtual-machine:/home/bshui/Python# ls
9x9.py  guess.py

9)資料夾相關操作
建立資料夾:os.mkdir(“test”)
獲取當前目錄:os.getcwd()
改變預設目錄:os.chdir(“../”)
獲取目錄列表:os.listdir(“./”)
刪除檔案Los.rmdir(“test”)

>>> import os
>>> os.mkdir("test")
>>> os.getcwd()
'/home/bshui/Python'
>>> os.chdir("./test")
>>> os.getcwd()
'/home/bshui/Python/test'
>>> os.listdir("./")
[]
>>> os.chdir("../")
>>> os.listdir("./")
['9x9.py', 'guess.py', 'test']
>>> os.rmdir("test")
>>> os.listdir("./")
['9x9.py', 'guess.py']

11.面向物件

面向過程:根據業務邏輯從上到下寫程式碼
面向物件:將資料與函式繫結到一起,進行封裝,減少重複程式碼的重寫過程
類:具有相同內部狀態和運動規律的實體集合
物件:一個具體事物的存在,可以直接使用
類就是建立物件的模板
1)類Class由3個部分構成
類的名稱:類名
類的屬性:一組資料
類的方法:允許物件進行操作的方法

#!/usr/bin/python3
class Car:
    def getCarInfo(self):
        print("the car's whell:%d color%s"%(self.wheelNum,self.color))

    def move(self):
        print("the car is moving...")


BMW = Car()  #建立一個物件,並用變數BMW來儲存它的引用
BMW.color = "black"
BMW.wheelNum = 4 #給物件新增屬性
BMW.getCarInfo() #呼叫物件的方法
BMW.move()
# ./car.py 
the car's whell:4 colorblack
the car is moving...

2)init()方法
在建立物件的時候,順便把物件的屬性給設定好

#!/usr/bin/python3
class Car:
    def __init__(self,newWheelNum,newColor):
        self.wheelNum = newWheelNum
        self.color = newColor
    def getCarInfo(self):
        print("the car's whell:%d color%s"%(self.wheelNum,self.color))

    def move(self):
        print("the car is moving...")


BMW = Car(4,"green")
BMW.getCarInfo()
BMW.move()
# ./car.py 
the car's whell:4 colorgreen
the car is moving...

3)self的理解,可以理解為自己,當物件呼叫一個方法時,python直譯器會把這個物件作為第一個引數傳遞給self,所以開發者只需要傳遞後面的引數即可
總結:Python沒有public,private關鍵字區別公有和私有屬性
它是以屬性命名方式來區分的,如果在屬性名前加2個__下劃線,則表明該屬性是私有屬性,否則為公有屬性(方法也一樣)
4)del方法

建立物件後,python直譯器預設呼叫 __init__()方法
當刪除一個物件時,python直譯器也會預設呼叫 __del__()方法

5)繼承

#!/usr/bin/python3
class Cat(object):
    def __init__(self,name,color="white"):
        self.name  = name
        self.color = color

    def run(self):
        print("%s...is running"%self.name)

class Bosi(Cat):
    def setNewName(self,newName):
        self.name = newName
    def eat(self):
        print("%s---is eating"%self.name)

bs = Bosi("Mick")
print("bs name is :%s color is:%s"%(bs.name,bs.color))
bs.eat()
bs.setNewName("bscat")
bs.run()
# ./cat.py 
bs name is :Mick color is:white
Mick---is eating
bscat...is running

子類在繼承的時候,在定義類時,小括號()中為父類的名字
父類的屬性,方法,會被繼承給子類
私有的屬性,方法不會被子類繼承,也不能被訪問
6)多繼承
python中可以多繼承,父類中的方法,屬性,子類會繼承
子類在繼承的時候,在定義類時,小括號()中為多個父類的名字用逗號隔開
7)重寫父類的方法
在子類中,有一個和父類相同名字的方法,在子類中的方法會覆蓋掉父類中同名的方法
7)多型
定義時的型別和執行時的型別不一樣

12.異常

捕獲異常try…except…..

#!/usr/bin/python3
try:
    open("123.txt","r")
except IOError:
    print("no file found")
# ./test.py 
no file found

此程式看不到錯誤,因為用except捕獲到了IOError異常,並添加了處理方法
獲取異常的資訊描述

#!/usr/bin/python3
try:
    open("123.txt","r")
except IOError as result:
    print(result)
# ./test.py 
[Errno 2] No such file or directory: '123.txt'

try…finally在程式中,如果一塊程式碼必須要執行,無論異常是否產生都要執行,需要使用finally

13.模組

模組:工具包,裡面有封裝好的函式
1)import 用關鍵字import來引入模組
當直譯器遇到import語句,如果模組在當前的搜尋路徑就會被匯入,在呼叫模組的函式時,用模組名.函式名

>>> import math
>>> math.sqrt(2)
1.4142135623730951
>>> math.sqrt(4)
2.0

2)from 模組名 import函式名1,函式名2
只需要用到模組中的其中的函式,引入該函式即可
不僅可以引入函式,還可以引入一些全域性變數,類等
3)from …import *
把一個模組的所有內容全都匯入到當前的名稱空間
from modname import * (一般不這樣用)

14.模組製作

在Python中,每個Python檔案都可以作為一個模組,模組的名字就是檔案的名字

# cat add.py 
def add(a,b):
    return a+b
# cat test.py 
#!/usr/bin/python3
import add

result = add.add(11,22)
print(result)
# ./test.py 
33

15.Python中的包

包將有聯絡的模組組織在一起,放到同一個資料夾下,並且在這個資料夾下建立一個名為init.py檔案,這個資料夾就稱為包

# ls mymath/
add.py  __init__.py  __pycache__  sub.py
# cat mymath/__init__.py 
__all__ = ["add","sub"]
# cat test.py 
#!/usr/bin/python3
from mymath import *  #匯入包
result = add.add(11,22)
print(result)
result = sub.sub(11,22)
print(result)
# ./test.py 
33
-11

16.模組的釋出

1)目錄結構

# ls -l
total 8
drwxr-xr-x 3 root root 4096 515 09:47 mymath
-rwxrwxrwx 1 root root  101 515 09:57 setup.py
# ls mymath/
add.py  __init__.py  __pycache__  sub.py

2)編輯setup.py檔案
py_modules需指明所需包含的py檔案

# cat setup.py 
from distutils.core import setup

setup(name="bshui",version="1.0",description="test mymath module")

3)構建模組

# python3 setup.py build
生成釋出壓縮包
# python3 setup.py sdist
# ls dist/
bshui-1.0.tar.gz

4)安裝模組
找到模組的壓縮包,解壓,進入目錄
執行python setup.py install

# python3 setup.py install
running install
running build
running install_egg_info
Removing /usr/local/lib/python3.5/dist-packages/bshui-1.0.egg-info
Writing /usr/local/lib/python3.5/dist-packages/bshui-1.0.egg-info

5)模組的引入
使用from import 可完成對安裝的模組的使用
from 模組名 import 模組名或者*