iT邦幫忙

3

Django學習紀錄 0.導讀 1.Python第一章就Go

  • 分享至 

  • xImage
  •  

之前有在用Django寫一些小網站,現在暑假想說再來複習一下之前買的這本書
https://ithelp.ithome.com.tw/upload/images/20190724/20118889bj9fH1vhuR.jpg
於是我就把它寫成一系列的文章,也方便查語法
而且因為這本書大概是2014年出的,如今Django也已經出到2.多版
有些內容也變得不再支援或適用,而且語法或許也改變了
所以我會以最新版的Python和Django來修正這本書的內容跟程式碼

目錄:django系列文章-Django學習紀錄

0.導讀

作者推薦的html學習網站
https://www.w3schools.com/html/default.asp
此書範例碼作者放置處
https://github.com/myyang/mysite

1.Python第一章就Go

1.1 Python特性與應用

1.1.1 動態語言

1.1.2 直譯語言

1.1.3 強定型的語言

1.1.9 Python的版本

1.2 Python的下載與安裝

CPython直譯器

Python官方網站: https://www.python.org/
開啟命令提示字元,輸入指令

python --version

如果python安裝成功,可以查看目前python版本
https://ithelp.ithome.com.tw/upload/images/20190711/20118889RxGLvbwXQZ.png
若出現這樣的錯誤訊息
https://ithelp.ithome.com.tw/upload/images/20190711/20118889aGYuTnyMvv.png
代表你的環境變數設置可能有問題

設定環境變數

電腦(右鍵)->內容->進階系統設定->環境變數->選取系統變數Path->編輯->加入指令路徑->確認設定
https://ithelp.ithome.com.tw/upload/images/20190802/201188893lzYrukESv.png
確認這兩個有被加進來
C:\Users\user\AppData\Local\Programs\Python\Python37-32\Scripts
C:\Users\user\AppData\Local\Programs\Python\Python37-32
注意,設定更改後,需重新開啟命令提示字元,變更才會生效喔!

1.3.1 進入 Python shell

輸入

python

https://ithelp.ithome.com.tw/upload/images/20190711/20118889sEzKPH2K63.png

1.3.2 Python的文件與求助

可以用

help()

指令來查詢函式,例如查詢sorted這個函式https://ithelp.ithome.com.tw/upload/images/20190711/201188899gh8aUPspS.png
如果要離開python shell
輸入指令 Ctrl+Z 就行
https://ithelp.ithome.com.tw/upload/images/20190711/20118889SxvR7EehcZ.png

1.3.3 關於運算

1.3.4 關於變數

1.3.5 關於資料型態 : None型態

1.3.6 關於變數參照

1.3.7 撰寫多個運算

使用記事本或其他文字編輯器將程式撰寫好後存成.py檔
開啟命令提示字元
利用以下指令切換目錄

cd 要進入的目錄

回到上一個目錄

cd..

在當前目錄建立新目錄

md 要建立的目錄名稱

或是

mkdir 要建立的目錄名稱

切到D槽

D:

進到檔案所在目錄後,輸入以下指令執行python程式

python test.py

小提醒,書上的

print result 

這個是python2.X的寫法,如果在python3.X 須改為

print(result)

1.3.8 封裝

1.3.9 類別與物件

1.4 資料型態

1.4.1 整數(Integer)與浮點數(Float)

取次方 **
/ 這裡要注意一下在python2.X中,如果/兩邊為整數,會變為取商;
在python3.X中,/則為正常除法,python3.X中的取商為//
https://ithelp.ithome.com.tw/upload/images/20190711/20118889nVlkjXM82i.png
科學記號表示法
1.2乘以10的2次方=120
https://ithelp.ithome.com.tw/upload/images/20190711/20118889vGohYqzHyu.png

doc string

使用三雙引號(或單引號)來製造跨行的字串
https://ithelp.ithome.com.tw/upload/images/20190711/20118889rqqZdb9vK6.png

1.4.3 字串(String)

字串的格式化

'My name is {0}, I am {1} years old.'.format('dokelung', 27)

或是

'My name is {name}, I am {age} years old.'.format(name='dokelung', age=27)

結果同樣都是
https://ithelp.ithome.com.tw/upload/images/20190711/20118889WDbvc2ubop.png

使用中文時的編碼問題

在python2.X中如果要使用非英文的字串,需在python檔案的最開頭加上

# -*- coding: utf-8 -*-

否則可能會產生錯誤

1.4.4 清單(List)

List中的元素為可變動的

1.4.5 元組(Tuple)

Tuple中的元素為不可變動的,如果嘗試去更動,將會出現TypeError的錯誤
撰寫單元素的Tuple時,記得要加上一個分隔的逗號

t = (1,)

1.4.6 字典(Dictionary)

不可變的資料可以當作鍵,所有資料可以當作值

1.4.8 使用群集的好處

群集物件可以利用sum()這個函式來加總元素

1.4.9 可變與不可變 (python中的重要觀念 !)

1.5 運算

1.5.1 賦值運算

其實就是讓左邊的變數參照右邊的資料

1.5.2 空運算

當要表示什麼都不做時,可以使用pass,常用於try except例外捕捉

1.5.3 自運算與增強運算

自運算 : a = a + 1 這類的運算
增強運算 : 自運算的簡化寫法例如 a += 1

1.5.4 比較運算

在python中可以同時使用兩個運算符來判定數值大小
例如0 < a <= 5 ,如果是在C/C++中就必須得寫成a > 0 && a <= 5呢!

1.5.6 身分運算

身分運算is可以用來判斷兩個資料是否來自於同一個記憶體位置,也就是兩個資料是不是同一個
==只能用來判斷兩個資料的"值"相等而已
https://ithelp.ithome.com.tw/upload/images/20190711/201188898vS7Dej96F.png
當兩個不同的變數被賦值不可變的相同資料時,其實是將這兩個變數參照到這個資料,所以==is都是True,而當兩個不同的變數被賦值可變的相同資料時,python會產生一個新的資料,所以==Trueis為False

1.5.7 隸屬運算 : in

1.6 流程控制

1.6.1 有條件的運算

區塊程式碼(Block,或在python中被稱為suite)
簡潔的if/else寫法 :

string = '現在是春季' if 3 <= month <= 5 else '現在不是春季'

1.6.2 重複的運算

list Comprehension

假設今天有一個list

lst = [1, 2, 3, 4, 5]

如果我們想要製造另一個list,每個元素是list元素的的平方

lst_sq = []
for num in lst:
    lst_sq.append(num**2)

簡潔的寫法:

lst_sq = [num**2 for num in lst]

這種寫法就是所謂的list comprehension
我們還可以加入條件判斷,只留下偶數的平方數

lst_sq = [num**2 for num in lst if num%2==0]

dictionary comprehension

scores = [88, 90, 100, 65, 78]
score_dic = {student_id:score for student_id, score in enumerate(scores)}

enumerate()這個函式和for搭配可以把元素的索引跟元素取出來用兩個變數迭代

1.7 輸入與輸出

print預設會輸出換行,如果不想換行必須這樣寫
(python2.X)

print 1,
print 2,
print 3

(python3.X)

print(1, end='')

檔案讀寫

假設有一個檔案test_file

Hello world
Today is a good day!

open函式預設是用來"讀取"檔案
利用readline一行一行讀取檔案,不過要注意的是連同結尾的換行符號'\n'也會讀取到
使用完畢記得close()關檔,否則會讓檔案佔住記憶體空間,導致不可預期的錯誤

f = open('test_file')
print(f.readline())
print(f.readline())
f.close()

output:

Hello world

Today is a good day!

如果要去除空白行可以使用strip()函式,這個函式可以清除字串頭尾的空白及換行

f = open('test_file')
print(f.readline().strip())
print(f.readline().strip())
f.close()

output:

Hello world
Today is a good day!

readline是一行接著一行下去讀取,如果要回去讀取前面的行,我們可以使用seek()函式

f = open('test_file')
print(f.readline().strip())
print(f.readline().strip())
f.seek(0)
print(f.readline().strip())
f.close()

seek(0)代表回到第0行(第1行)
output:

Hello world
Today is a good day!
Hello world

也可以和for搭配

f = open('test_file')
for line in f:
    print(line.strip())
f.close()

python的"環境管理器"功能,透過with as簡化我們的檔案讀寫

with open('test_file') as f:
    for line in f:
        print(line.strip())

使用這種寫法就可以忽略檔案關閉,因為一旦離開with的suite,檔案就會被自動關閉了
如果要寫檔的話,多加一個參數'w'
(python2.X)

lst = ['第一行', '第二行']
with open('test_file', 'w') as f:
    for line in lst:
        print >> f, line

(python3.X)

lst = ['第一行', '第二行']
with open('test_file', 'w') as f:
    for line in lst:
        print(line, file=f)

1.8 例外與捕捉

有一檔案test_file

3 4
1 3

20 19
%%%
88 7
1 2 3
0

若想對只有兩個數字的行求和,使得output變這樣

7
4
39
95

則我們可以這樣寫

with open('test_file') as f:
    for line in f:
        try:
            a, b = line.strip().split() # 這種寫法稱為unpack
            print(int(a)+int(b))
        except ValueError:
            pass # 空運算

1.9 函式

1.9.1 內建函式

工廠函式

將資料轉成另一種型態的函式,例如int() float() str()
其他還有像是
bool()
將資料轉為布林值
list()
將資料轉為list
set()
製造集合或將資料轉為集合,這是一個很簡便的方法可以將list中重複的元素過濾掉

全部或任何

pass = [True, True, True, False, False]

今天我們想知道全班所有人是不是都及格,傳統的做法是:

all_pass = True
for s in pass:
    if s==False:
        all_pass = False
if all_pass:
    print('歐趴')
else:
    print('有人不及格')

使用all()函式簡化運算,當全部都為真回傳True,否則回傳False

if all(pass):
    print('歐趴')
else:
    print('有人不及格')

另一個函式any()則相反,只要有一個為真就回傳True

1.9.2 自定義函式

遞迴

有一個list

lst = [1, 2, [3, 4, 5], 6, [7, [8,9]]]

如果我們想要印出其中的每一個數字而不把它以list的形式印出來
我們可以利用遞迴的方式

def print_list(lst):
    for item in lst:
        if isinstance(item, list): # 如果item是list型態就回傳True,否則回傳False
            print_list(item)
        else:
            print(item)

1.9.3 綴星運算式

一個加法函式

def add(a, b, c, d):
    return a+b+c+d

如果我們要把一個list裡的所有元素相加
我們可以這樣寫

lst = [1, 2, 3, 4]
print(add(*lst)) # *lst會執行unpacking(拆解)的動作

如果要寫一個不限定參數個數的求和函式,我們可以這樣寫

def add(*tup): # 將傳進來的所有元素組成一個tuple
    return sum(tup)
print(add(1, 2, 3, 4))

也可用於字典

def power(base, exp):
    return base ** exp
dic = {'base':2, 'exp':3}
print(power(**dic)) # 拆解成base=2 exp=3
def power(**dic):
    return dic['base'] ** dic['exp']
print(power(base=2, exp=3)) # 形成字典 {'base':2, 'exp':3}

1.9.5 閉包與裝飾器

閉包(Closure)是參照了外部環境的函式,舉例

def gen_power(base):
    def power(exp): # 區域函式,power函式就是閉包
        return base ** exp
    return power
power2 = gen_power(2)
power3 = gen_power(3)
print(power2(3)) # 8
print(power3(2)) # 9

這種方法又被稱為揉製(curry)

裝飾器

def print_result(func):
    def modified_func(*args):
        print(args)
        print(func(*args))
    return modified_func

@print_result
def add(*tup):
    return sum(tup)

@print_result
def power(base, exp):
    return base ** exp

add(1, 2, 3, 4, 5) # 相當於 add = print_result(add)
power(2, 3) # 相當於 power = print_result(power)

印出結果

(1, 2, 3, 4, 5)
15
(2, 3)
8

在裝飾器裡增加一些參數

def print_result(head):
    def decorator(func):
        def modified_func(*args, **kwargs):
            result = func(*args, **kwargs)
            print(head, result)
        return modified_func
    return decorator

@print_result(head='result:')
def add(*tup):
    return sum(tup)

add(1, 2, 3, 4, 5) # 相當於 add = print_result(head='result:')(add)

印出結果

result: 15

下一篇:Django學習紀錄 2.Python的模組與套件


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言