1. 程式人生 > 其它 >《Python小白書》學習筆記(更新中)

《Python小白書》學習筆記(更新中)

技術標籤:Pythonpython

文章持續更新中…

文章目錄

0 – Python簡介

1 Python簡介

1 Python是解釋型語言:無需編譯

2 Python是互動式語言:可以在>>>提示符後直接執行程式碼

3 Python是面向物件語言:Python支援 1面向物件的風格 2程式碼封裝在物件 的程式設計技術

4 Python是初學者的語言:容易上手,支援廣泛的應用程式

2 Python的10個特點

1 易於學習:Python有相對較少的關鍵字,結構簡單,和一個明確定義的語法,學習起來更加簡單。

2 易於閱讀:Python程式碼定義的更清晰。
3 易於維護:Python的成功在於它的原始碼是相當容易維護的。
4 一個廣泛的標準庫:Python的最大的優勢之一是豐富的庫,跨平臺的,在UNIX,Windows和Macintosh相容很好。
5 互動模式:互動模式的支援,您可以從終端輸入執行程式碼並獲得結果的語言,互動的測試和除錯程式碼片斷。
6 可移植性:基於其開放原始碼的特性,Python已經被移植(也就是使其工作)到許多平臺。
7 可擴充套件性:如果你需要一段執行很快的關鍵程式碼,或者是想要編寫一些不願開放的演算法,你可以使用C或C++完成那部分程式,然後從你的Python程式中呼叫。
8 資料庫:Python提供所有主要的商業資料庫的介面。
9 GUI程式設計:Python支援GUI可以建立和移植到許多系統呼叫。
10 可嵌入:你可以將Python嵌入到C/C++程式,讓你的程式的使用者獲得"指令碼化"的能力。

3 常用的庫(持續更新…)

NumPy https://www.numpy.org.cn
Pandas https://www.pypandas.cn
Matploplib https://www.matplotlib.org.cn

4 入門學習推薦(持續更新…)

runoob 菜鳥教程

《程式設計小白的第一本Python入門書》 # 簡單易懂,偶爾有點小錯誤

《Python程式設計從入門到實踐》 # 經典入門書籍

《笨辦法學Python3》 # 經典入門書籍

《Python程式設計快速上手 讓繁瑣工作自動化》 # 自動化辦公,進階圖書

《流暢的Python》 # 進階圖書

《Python》袖珍指南 # 工具書


1 – 變數與字串

1 前提

1 區分大小寫

2 句末無需新增分號

3 在shell中開啟Python:輸入Python3

4 Python 3 原始碼檔案以UTF-8編碼,所有字串都是UNICODE字串

5 解決中文註釋報錯問題:檔案開頭新增一行#coding:utf-8

6 註釋的三種方法:# ''' """

7 多行語句,使用反斜槓\

2 四種數字型別

int bool float complex

3 變數

識別符號必須以字母下劃線開頭

識別符號的其他的部分由字母、數字和下劃線組成

識別符號對大小寫敏感

# 識別符號answer、賦值符=、值42
answer = 42

# 保留字不可以用作識別符號,查詢方法:
import keyword
keyword.kwlist
* 基礎的實用函式
print(<變數名>)    # 列印
input(<變數名>)    # 輸入
type(<變數名>)     # 返回變數的型別
len(<變數名>)      # 返回字串的長度
4 字串

三種寫法:'' "" '''<無限長度的字串,隨意換行>'''

不區分char和string型別,''""基本等價;"abcd'e'fgh"雙引號中可以直接包含單引號,無需轉義

轉義符\

字串用+連線,用*重複

兩種索引方式:從左往右以0開始,從右往左以-1開始

分片:截取出一段字串,複製出一個副本,不會改動原字串

字串的擷取格式:變數[頭下標:尾下標:步長]

abcdefghijklmnp
01234567891011121314
-15-14-13-12-11-10-9-8-7-6-5-4-3-2-1
# <程式碼示例> +和*
str1 = 'aaa'
str2 = 'bbb'
print(str1+str2, str1*2, str2*3)      #aaabbb aaaaaa bbbbbbbbb

# <程式碼示例> 轉義符 r'\'
print('abcde')      #abcde
print('abc\nde')    #abc(換行)de   #\n代表換行,反斜槓(\)將字母(n)轉義為換行符
print(r'abc\nde')   #abc\nde      #r=raw string 取消轉義,輸出''中的全部內容

# <程式碼示例> 索引和分片;對照表格
name = 'abcdefghijklmnp'
len(name)
print(name, name[0:])          #abcdefghijklmnp abcdefghijklmnp
print(name[0], name[-15])      #a a   #正數第0位,倒數第-15位
print(name[14], name[-1])      #p p   #正數第14位,倒數第-1位
print(name[0:5], name[1:5])    #abcde bcde   #[頭下標:共擷取n位]
print(name[5:], name[:5], name[-5:])      #fghijklmnp abcde klmnp
5 字串的常用方法

物件、方法

replace() 替換

find() 返回子字串第一位在母字串的位置

format() 字串格式化符

# <程式碼示例> replace()
phone_num = '1234-567-890'
hiding_num = phone_num.replace( phone_num[:9], '*'*9 )
print(hiding_num)

# <程式碼示例> find()
search = '168'
num_a = '1386-168-0006'
num_b = '1681-222-0006'
num_a.find(search)      #返回'168'的第一位在num_a中的位置,返回5,即第6位
print( search + ' is at ' + str(num_a.find(search)+1) \
       + ' to ' \
       + str( num_a.find(search)+len(search) ) \
       + ' of num_a.' )
print( search + ' is at ' + str(num_b.find(search)+1) \
       + ' to ' \
       + str( num_b.find(search)+len(search) ) \
       + ' of num_b.' )
#5
#168 is at 6 to 8 of num_a.   #5+1, 5+3
#168 is at 1 to 3 of num_b.   #0+1, 0+3

# <程式碼示例> format()
# 1
print( '{} a word she can get what she {} for.'.format('_'*5, '_'*5) )
print( '{} a word she can get what she {} for.'.format('With', 'came') )
print( '{0} a word she can get what she {1} for.'.format('With', 'came') )
print( '{str_1} a word she can get what she {str_2} for.'.format(str_1='With', str_2='came') )
#_____ a word she can get what she _____ for.
#With a word she can get what she came for.
#With a word she can get what she came for.
#With a word she can get what she came for.

# 2 輸入城市名稱並賦值到city中,將city名稱傳入url,則能夠使用百度提供的天氣API查詢當前天氣
city = input('Write down the name of city:')
url = "https://jisuweather.api.bdymkt.com/weather/{}".format(city)
print(url)
#(輸入)London
#https://jisuweather.api.bdymkt.com/weather/London
6 列表List
# <程式碼示例> 列表
# append() 向列表中插入內容
# 列表的索引,與字串基本一致,把列表中的每一個元素看作字串中的每一個字元
album = []
album = ['Black Star', 'David Bowie', 25, True]
album.append('new song')
print(album[0], album[-1])      #Black Star new song
print(album, album[0:], album[:3])

2 – 函式

一、內建函式

1 常用的內建函式
print()
input()
len()
#型別轉換
type()
int()
bool()
float()
complex()
str()
#attribute屬性
getattr()
hasattr()
setattr()
2 Python3的內建函式-69個

參考1:https://docs.Python.org/3/library/functions.html

參考2:https://www.runoob.com/python/python-built-in-functions.html

#Built-in Functions
# A -4
abs()
all()
any()
ascii()
# B -4
bin()
bool()
breakpoint()
bytearray()
bytes()
# C -5
callable()
chr()
classmethod()
compile()
complex()
# D -4
delattr()
dict()
dir()
divmod()
# E -3
enumerate()
eval()
exec()
# F -6
filter()
float()
format()
frozenset()
# G -6
getattr()
globals()
hasattr()
hash()
help()
hex()
# I -6
id()
input()
int()
isinstance()
issubclass()
iter()
# L -3
len()
list()
locals()
# M -4
map()
max()
memoryview()
min()
# N -1
next()
# O -4 
object()
oct()
open()
ord()
# P -3 
pow()
print()
property()
# R -4
range()
repr()
reversed()
round()
# S -8
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()
# T -2
tuple()
type()
# V -1
vars()
# Z -1
zip()
# * -1
__import__()
3 數學運算子
+ - * /    #四則運算
//    #返回商的整數部分
%     #模運算,求餘數
**    #冪運算,與pow(a,b)用法相同

二、自定義函式

1 建立函式

注意:半形英文冒號,return前需要縮排

# <TEMPLATE> 建立函式
# def-definition; args-引數
def function(arg1, arg2):
    return <Something>

# <程式碼示例>
# (1) 攝氏度轉換成華氏度,呼叫輸入的值
def C2H(C):
    H = C * 9/5 + 32
    return str(H) + 'H'
celsius = input('Input Celsius:')      #35
print( C2H(int(celsius)) )             #95.0H

# (2) 重量轉換器:g轉換成kg
def G2KG(G):
    KG = G/1000
    return print(str(KG) + 'KG')
G2KG(1520)      #1.52KG

# (3) 計算直角三角形斜邊的長度
def Triangle(a, b):
    c = pow(a*a+b*b, 0.5)
    return print(c)
Triangle(3,4)      #5.0
2 傳遞引數與引數型別
# 傳遞引數的兩種方式
# (1)位置引數 - positional argument
def function(arg1, arg2, arg3):
    return <>
# (2)關鍵詞引數 - keyword argument
def function(arg1=1, arg2=2, arg3=3):
    return <>

# 呼叫格式
function(1, 2, 3)                  #RIGHT! 引數按位置依次傳入
function(arg1=3, arg2=2, arg3=1)   #RIGHT! 引數反序傳入,但關鍵詞引數打亂順序不影響函式執行
function(1, 2, arg3=3)             #RIGHT! 引數正序傳入
function(1, 2)                     #RIGHT! 引數正序傳入,預設關鍵詞引數
function(arg3=3, arg2=2, 1)        #WRONG! 引數反序傳入,其中包含位置引數,順序不對,報錯
function(arg1=1, arg2=2, 3)        #WRONG! 位置引數不能置於關鍵詞引數後面
# 檔案操作
file = open('/Users/apple/Desktop/text.txt', 'w')
file.write('Hello World!')
file.close()
#Hello World!

# <程式碼示例>
# 1 在桌面建立自命名的txt檔案,同時寫入資料
def text_create(name, msg):
    desktop_path = '/Users/apple/Desktop/'
    full_path = desktop_path + name + '.txt'
    file = open(full_path, 'a+')
    file.write(msg)
    file.close()
    print('DONE!')
text_create('hello', 'hello world!')
#桌面出現名為hello.txt的文字檔案,第一行出現hello world!

# 2 關鍵字過濾,使用replace()
def text_filter(word, censored_word = 'lame', changed_word = 'AWESOME'):
    return word.replace(censored_word, changed_word)
text_filter('Python is lame!')
#Python is AWESOME!

# 3 在新函式中呼叫前兩個函式
def text_filter_create(name, msg):
    msg = text_filter(msg)
    print(msg)
    text_create(name, msg)
text_filter_create('test', 'Python is lame.\n')
text_filter_create('test', 'Python is lame.\n')
#Python is Awesome!
#Python is Awesome!

3 – 迴圈與判斷

一、判斷

1 邏輯判斷
# 比較運算子
# 不同型別之間只能使用 == 和 != 進行比較
# True=1 False=0 所以 True>False
== !=
> <
>= <=

# 成員運算子,等價於==
is
# 身份運算子
in
# 布林運算子
not
and
or
2 if-else語句
# <TEMPLATE> if-else
# <condition>返回值為True
if <condition>:
    <do something>
elif <condition>:
    <do something>
else:
    <do something>
# <程式碼示例> if-else 密碼
password_list = ['*#*#', '12345']

# 建立函式:輸入密碼-登入成功/改密碼
def account_login():
    password = input('Password:')
    password_true = (password == password_list[-1])
    password_reset = (password_list[0])
    if password_true:
        print('Login Success!')
    elif password_reset:
        new_password = input('Wrong! Enter a new password:')
        password_list.append(new_password)
        print('Your password has changed successfully!')
        account_login()
    else:
        print('Wrong password or invalid input!')
        account_login()

account_login()

二、迴圈

1 for迴圈
# <TEMPLATE> for
for <變數名> in <可迭代的集合>:
    <do something>

# <程式碼示例> 列印九九乘法表
for i in range(1,10):
    for j in range(1,10):
        print('{} * {} = {}'.format(i,j,i*j))
2 while迴圈
# <TEMPLATE> while
while <條件>:
    <do something>
    
# <程式碼示例> 
# (1)死迴圈。條件永遠為真,需要強制停止執行
while 1:
    print('Infinite Loop! 死迴圈環環環環...')
# (2)執行5遍,break跳出迴圈
cnt1 = 0
while 1:
    print('隨便寫點什麼1')
    cnt1+=1
    if (cnt1 == 5):
        break

cnt2 = 0
while (cnt2 < 5):
    print('隨便寫點什麼2')
    cnt2+=1
3 練習題
# 簡單的習題
# Practice 1 -- 在桌面建立10個txt,並以數字的順序命名
for count in range(1,11):
    file = open('/Users/apple/Desktop/{}.txt'.format(count), 'a')
    file.close()
    print(str(count) + '.txt FINISHED')

# Practice 2 -- 複利:A(1+x)^t=B
def invest(amount, rate, time):
    print('principal amount: ' + str(amount))
    for count in range(1,time+1):
        invest = ((1+rate*0.01)**count) * amount
        print('year '+ str(count) + ': $' + str(invest))
        count+=1
invest(100,5,8)

# Practice 3 -- 列印1~100內的偶數
for count in range(1,101):
    if (count%2==0):
        print(count)
# 練習題:註冊賬戶時,為了正確傳送驗證碼,判斷輸入的電話號碼
CN_mobile = ['134','135','136','137','138','139','150','151','152','157','158','159','182','183','184','187','188','147','178','1705']
CN_union = ['130','131','132','155','156','185','186','145','176','1709']
CN_telecom = ['133','153','180','181','189','177','1700']

def SIGNIN():    
    num = input('Enter Your Number: ')
    
    if len(num) == 11:
        if (num[0:3] in CN_mobile) or (num[0:4] == '1705'):
            print('Operator: China Mobile\n'+str(num)+' Verification Code Sended.')
        elif (num[0:3] in CN_union) or (num[0:4] == '1709'):
            print('Operator: China Union\n'+str(num)+' Verification Code Sended.')
        elif (num[0:3] in CN_telecom) or (num[0:4] == '1700'):
            print('Operator: China Telecom\n'+str(num)+' Verification Code Sended.')
        else:
            print('No such an operator!\n')
            SIGNIN()            
    else:
        print('Invalid lengthm your number shoulde be in 11 digits.\n')
        SIGNIN()

4 – 資料結構

一、四種資料結構

列表list 字典dict 元組tuple 集合set

1 列表 list = []

每一個元素都是可變的

元素有序

可以容納Python中的任何物件

可以通過分片來查詢 [a:b],只能用位置進行索引

類比陣列

# list[]的增刪改查
# 增
<list>.insert('~', '~')
# 刪
<list>.remove('~')
del <list>[i:j]
# 改
list[i] = '~'
# 查:列表只接受用位置進行索引
2 字典 dict = {}

key-value 鍵值對

字典中資料必須以鍵值對的形式出現

鍵不能重複,值可以重複

鍵不可變,無法修改;值可變、可修改,可以是任何物件

不能通過分片來查詢

# dict{}的增刪改查
#增
<dict>[key] = {value}
<dict>.update( {key1:value1, key2:value2} )
#刪
del <dict>[]
#查
<dict>[key]

3 元組 tuple

穩固版的列表,不可修改,可以檢視索引

4 集合 set

集合中的元素是無序、不重複的任意物件

不能切片、不能被索引

可以做集合運算

集合元素可以被新增、刪除

二、資料結構的基礎技巧

1 多重迴圈
2 推導式
3 迴圈列表時獲取元素的索引
4 綜合專案