Django学习纪录 0.导读 1.Python第一章就Go

之前有在用Django写一些小网站,现在暑假想说再来複习一下之前买的这本书
http://img2.58codes.com/2024/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版本
http://img2.58codes.com/2024/20118889RxGLvbwXQZ.png
若出现这样的错误讯息
http://img2.58codes.com/2024/20118889aGYuTnyMvv.png
代表你的环境变数设置可能有问题

设定环境变数

电脑(右键)->内容->进阶系统设定->环境变数->选取系统变数Path->编辑->加入指令路径->确认设定
http://img2.58codes.com/2024/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

http://img2.58codes.com/2024/20118889sEzKPH2K63.png

1.3.2 Python的文件与求助

可以用

help()

指令来查询函式,例如查询sorted这个函式http://img2.58codes.com/2024/201188899gh8aUPspS.png
如果要离开python shell
输入指令 Ctrl+Z 就行
http://img2.58codes.com/2024/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中的取商为//
http://img2.58codes.com/2024/20118889nVlkjXM82i.png
科学记号表示法
1.2乘以10的2次方=120
http://img2.58codes.com/2024/20118889vGohYqzHyu.png

doc string

使用三双引号(或单引号)来製造跨行的字串
http://img2.58codes.com/2024/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)

结果同样都是
http://img2.58codes.com/2024/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可以用来判断两个资料是否来自于同一个记忆体位置,也就是两个资料是不是同一个
==只能用来判断两个资料的"值"相等而已
http://img2.58codes.com/2024/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 worldToday is a good day!

open函式预设是用来"读取"档案
利用readline一行一行读取档案,不过要注意的是连同结尾的换行符号'\n'也会读取到
使用完毕记得close()关档,否则会让档案佔住记忆体空间,导致不可预期的错误

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

output:

Hello worldToday is a good day!

如果要去除空白行可以使用strip()函式,这个函式可以清除字串头尾的空白及换行

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

output:

Hello worldToday 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 worldToday 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 41 320 19%%%88 71 2 30

若想对只有两个数字的行求和,使得output变这样

743995

则我们可以这样写

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 = Truefor s in pass:    if s==False:        all_pass = Falseif 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 ** expdic = {'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 powerpower2 = gen_power(2)power3 = gen_power(3)print(power2(3)) # 8print(power3(2)) # 9

这种方法又被称为揉製(curry)

装饰器

def print_result(func):    def modified_func(*args):        print(args)        print(func(*args))    return modified_func@print_resultdef add(*tup):    return sum(tup)@print_resultdef power(base, exp):    return base ** expadd(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的模组与套件


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章