Python學習總結一:基礎篇
目錄
- Python學習總結一:基礎篇
Python學習總結一:基礎篇
<說明>
操作平臺:DeepinLinux OS 15.7
版本選擇:Python3.6.5
適用人群:有基本的計算機基礎
0.Python3安裝使用
Linux預設安裝是Python2.x,在控制檯輸入程式碼檢視是否安裝了Python3:
$ python3 Python 3.6.5 (default, May 11 2018, 13:30:17) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
若出現這個結果,說明已經安裝成功,否則要自行安裝:
$ sudo apt-get install python3
使用和退出
# 使用 $ python3 # 退出 Ctrl + D 或者 exit()
1.Python規則
- 1.用4個空格縮排(或設定好一個tab鍵為4個空格)
- 2.不要混用空格和製表符
- 3.函式之間空一行,類之間空兩行
- 4.運算子周圍1個空格
- 5.字典,元組,列表逗號後1個空格;字典冒號後1個空格
- 6.註釋符#後1個空格
- 7.不要出現多餘的空格,用縮排區分語句塊
2.第一個Python3檔案
su - root# 輸入密碼後進入root模式 vim xx.py# 建立.py檔案 chmod +x xx.py# 賦予該檔案執行許可權 ./xx.py# 執行檔案 或者用記事本或者其他編輯器建立儲存.py檔案 進入該檔案目錄執行 python3 xx.py
檔案格式:
#!/usr/bin/env python3# 呼叫Python的直譯器 python code ...
3.變數和簡單的資料型別
3.1變數命名
變數命名規則
- 變數名只能包含數字、字母和下劃線,且不能以數字開頭
- 不能使用Python關鍵字和函式名作為變數名
- 慎用大小寫的L和O,可能會誤認為1和0
- 變數名應簡短具有描述性
檢視所有關鍵字
$ python3 >>> help() help> keywords Falsedefifraise Nonedelimportreturn Trueelifintry andelseiswhile asexceptlambdawith assertfinallynonlocalyield breakfornot classfromor continueglobalpass
3.2字串
用單引號‘’
或雙引號”“
引起來的內容就是字串
3.2.1常用方法
title()將首字母大寫、upper()全部大寫、lower()全部小寫,例如:
>>> name = "deemo liNUX" >>> name.title() 'Deemo Linux' >>> name.upper() 'DEEMO LINUX' >>> name.lower() 'deemo linux'
3.2.2字串的連線
使用加號+
連線即可,例如:
>>> one = "deemo" >>> two = "linux" >>> one + two 'deemolinux'
3.2.3避免錯誤
單引號裡有單引號,雙引號裡有雙引號,如:
>>> name = 'xyp'gg' File "<stdin>", line 1 name = 'xyp'gg' ^ SyntaxError: invalid syntax >>> name = "xyp"gg" File "<stdin>", line 1 name = "xyp"gg" ^ SyntaxError: invalid syntax
兩者混合使用即可,避免歧義,如:
>>> name = "xyp'gg" >>> print(name) xyp'gg
3.3數字
3.3.1整數
可進行加減乘除乘方等常規運算,如:
>>> 3 + 2 5 >>> 3 - 2 1 >>> 3 * 2 6 >>> 3 / 2 1.5 >>> 3 ** 2 9 >>> 3 ** 3 27
3.3.2浮點數
帶小數點的數稱為浮點數
3.3.3型別轉換
使用str()避免型別錯誤,如:
>>> age = 22 >>> print("Your age is:" + age) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be str, not int # 轉換後 >>> print("Your age is:" + str(age)) Your age is:22
3.3.4取模取餘
divmod(number1, number2) 返回兩個結果,第一個是number1 / number2
第二個是number1 % number2
>>> print("div={}, mod={}".format(*divmod(3, 2))) div=1, mod=1
4.註釋
使用#
進行註釋,註釋要簡明扼要,不能不註釋,但不要說太多廢話
5.列表
5.1列表簡介
5.1.1列表是什麼
列表由一系列按特定順序排列的元素組成,如
>>> namelist = ['deemo', 'linus', 'mark'] >>> print(namelist) ['deemo', 'linus', 'mark'] # 列表索引從0開始,訪問列表 >>> namelist[0] 'deemo' >>> namelist[2] 'mark' >>> print("My name is " + namelist[0].title() + "!") My name is Deemo!
5.1.2修改新增刪除元素
# 修改 >>> namelist[2] = 'jack' >>> namelist ['deemo', 'linus', 'jack'] # 新增(在末尾新增)append() >>> namelist.append('xiye') >>> namelist ['deemo', 'linus', 'jack', 'xiye'] # 插入(在指定位置新增,0是下標)insert() >>> namelist.insert(0, 'uzi') >>> namelist ['uzi', 'deemo', 'linus', 'jack', 'xiye'] # 刪除指定下標的元素 del >>> del namelist[0] >>> namelist ['deemo', 'linus', 'jack', 'xiye']
insert(下標, 元素) 實際上是在原來列表下標位置上插入新資料
而原來那個位置往後的資料都向後移動了一位
問題來了,del
刪除後這個值就消失了,如果想用這個值怎麼辦?
使用pop()
即可,把pop彈出的值賦給新變數,例如:
>>> namelist.pop() 'xiye'# 彈出後也就相當於刪除了 >>> namelist ['deemo', 'linus', 'jack'] >>> name_1 = namelist.pop() >>> name_1 'jack' >>> print("My name ever used is:" + name_1) My name ever used is:jack >>> namelist ['deemo', 'linus']
pop(下標):彈出指定位置的值
根據元素刪除值:remove()
>>> namelist.remove('deemo') >>> namelist ['linus']
5.1.3組織列表
sort():永久性排序(列表元素是排序後的順序)
>>> numbers = [1, 3, 2, 4] >>> numbers [1, 3, 2, 4] >>> numbers.sort() >>> numbers [1, 2, 3, 4]
sorted():臨時性排序(列表元素還是原來的順序)
>>> numbers = [1, 3, 2, 4] >>> numbers [1, 3, 2, 4] >>> sorted(numbers) [1, 2, 3, 4] >>> numbers [1, 3, 2, 4]
反轉列表元素,reverse()
>>> numbers [1, 3, 2, 4] >>> numbers.reverse() >>> numbers [4, 2, 3, 1]
列表長度,len()
>>> len(numbers) 4
5.1.4避免錯誤
使用列表時要避免索引錯誤,是從0開始
5.2列表操作
5.2.1遍歷列表
常規操作
namelist = ['alan', 'judis', 'carl'] for name in namelist: print(name)
遍歷列表同時輸出索引值 enumerate()
a = [1, 2, 3] for i, j in enumerate(a): print(i, j)
同時遍歷兩個列表 zip()
a = [1, 2, 3] b = ['a', 'b', 'c'] for x, y in zip(a, b): print("{} ---- {}".format(x, y))
5.2.2建立數值列表
使用函式range()和list()建立
>>> number = list(range(1, 6)) >>> number [1, 2, 3, 4, 5]
例子:生成列表數值的平方值列表
# 建立空列表,用於存放平方值資料 square = [] for value in range(1, 11): square.append(value ** 2) print(square)
range(start, stop, step)
start:初始值
stop:結束值,但不包括
step:步長
# 數值列表簡單操作 >>> min(number) 1 >>> max(number) 5 >>> sum(number) 15
5.2.3列表切片
>>> a = [1, 3, 2, 4, 5] >>> a [1, 3, 2, 4, 5] # 取出a[0]~a[2] >>> a[: 3] [1, 3, 2] # 取出a[0]~a[1] >>> a[0: 2] [1, 3] # 取出a[1]~a[3] >>> a[1: 4] [3, 2, 4] # 取出後三位 也就是a[-3]~a[-1]列表最後一位是a[-1] >>> a[-3:] [2, 4, 5]
5.2.4複製列表
定義新列表,把需要複製的列表直接賦值給新列表即可
new_list = old_list[]
6.元組
元組和列表不同處在於:
,
>>> a = (1, 2, 3) >>> a (1, 2, 3) >>> a[0] = 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
其他操作和列表類似,只是沒有列表靈活,適合用於不變的場景
7.if、while、for、input、print語句
7.1if、while、for語法
# 1.if語句 if exp: do this elif exp:# else if do this else: do this # 2.while語句 while condition: stat1 stat2 ... # 3.for語句 for x in a: stat ...
7.2input()方法
input():作用是暫停輸出,等待使用者輸入字串,儲存在變數內以便使用,例如:
name = input("Enter your name:") age = int(input("Enter your age:"))# age是整數int型別
7.3while中迴圈操作
while迴圈中break
退出迴圈,continue
繼續迴圈,例如:
#!/usr/bin/env python3 mess = "\nI will repeat your words those you enter," mess += "\nor you can enter 'quit' to quit:" while 1: message = input(mess) print(message) if message != "quit": continue else: break
結果:
$ python3 message_while.py I will repeat your words those you enter, or you can enter 'quit' to quit:Xypgg Xypgg I will repeat your words those you enter, or you can enter 'quit' to quit:quit quit
7.4print()方法
print(str)# 常規輸出 print(str, end='***')# 每次輸出以end後面的內容結尾 print()# 再帶換行效果,單獨使用相當於換一行 print("@" * 40)# 輸出40個@ 注: str.format() 格式化函式 字串格式化:將`{}`中的內容替換為format中的引數 數字格式化: - {:.2f} 2位精度的浮點數 - {:5d} 5字元寬的整數 - {:7.2f} 7字元寬,2位精度的浮點數
8.字典
8.1字典定義
字典是一系列鍵-值對組成的資料結構,鍵與值相關聯,可以使用鍵來訪問相關的值。
與鍵相關的值可以是數字、字串、列表甚至是字典。
字典用{鍵: 值, 鍵: 值, ....}
表示,例如:
>>> user = {'contury': 'china', 'language': 'chinese', 'color': 'yellow',} >>> user['color'] 'yellow'
8.2字典操作
8.2.1新增元素
>>> user['eatting'] = 'chopsticks' >>> user {'contury': 'china', 'language': 'chinese', 'color': 'yellow', 'eatting': 'chopsticks'}
8.2.2修改元素
>>> user['contury'] = 'England' >>> user {'contury': 'England', 'language': 'chinese', 'color': 'yellow', 'eatting': 'choopstiks'}
8.2.3刪除元素
>>> del user['eatting']# del >>> user {'contury': 'England', 'language': 'chinese', 'color': 'yellow'}
8.2.4遍歷所有鍵-值對
使用方法items()
>>> user {'contury': 'England', 'language': 'chinese', 'color': 'yellow'} >>> for key, value in user.items(): ...print("Key:" + key) ...print("Value:" + value) ... Key:contury Value:England Key:language Value:chinese Key:color Value:yellow
8.2.5遍歷所有鍵
使用方法keys()
>>> for key in user.keys(): ...print("Key:" + key) ... Key:contury Key:language Key:color
8.2.6遍歷所有值
使用方法values()
>>> for value in user.values(): ...print("Value:" + value) ... Value:England Value:chinese Value:yellow
8.2.7列表巢狀字典
>>> user_1 = {'color': 'white',} >>> user_2 = {'color': 'yellow',} >>> user_3 = {'color': 'black',} >>> user = [user_1, user_2, user_3] >>> for man in user: ...print(man) ... {'color': 'white'} {'color': 'yellow'} {'color': 'black'}
8.2.8字典巢狀列表
>>> user = {'language': ['Chinese', 'English', ], 'color': ['yellow'], } >>> user {'language': ['Chinese', 'English'], 'color': ['yellow']} >>> for x, y in user.items(): ...print("\nKey:" + x) ...for z in y: ...print("\t" + z) ... Key:language Chinese English Key:color yellow
8.2.9字典巢狀字典
#!/usr/bin/env python3 user = { 'xiaozhang': { 'color': 'yellow', 'language': 'Chinese', }, 'xiaoxi': { 'color': 'white', 'language': 'English', } } for name, info in user.items(): print("\nName:" + name) for x, y in info.items(): print("\t" + x + ":" + y)
結果是:
$ python3 markdown_user.py Name:xiaozhang color:yellow language:Chinese Name:xiaoxi color:white language:English
小結
Python基礎總結內容有:
- Python3的安裝與使用
- 變數和資料型別
- 列表
- 元組
- 字典
- if、for、while、input、print語句