0
点赞
收藏
分享

微信扫一扫

Python 笔记

覃榜言 2022-09-18 阅读 128

Python

简介

Python 由 Guido van Rossum(荷兰 🇳🇱)开发。

Python 是一门解释型语言、动态类型(弱类型)语言。

Python 的名字来源于 Monty Python's Flying Circus。

保存词

不能使用保存词(reserved words)来命名变量名称,这样的词有:

​False, class, return, is, finally, None, if, for, lambda, continue, True, def, from, while, nonlocal, and, del, global, not, with, as, elif, try, or, yield, assert, else, import, pass, break, in, raise​

Python 的关键字很接近自然语言:

  • ​True,False​​ 布尔值,相当于“真,假”,类似于其他语言中的​​true, false​​。
  • ​None​​ 相当与“空”,类似于其它语言中的​​null​​。
  • ​is,is not​​ 运算符用于逻辑表达式,前者的意思是“和什么相同”,相似于​​==​​,但是更强。​​is​​ 同时检查值和类型,常用在​​None​​ 或者布尔值的判断,类似 JavaScript 中的​​===​​。

0 == 0.0 # True
0 is 0.0 # False

构建块

赋值

赋值就是把变量名和数值联系起来,定义函数就是把函数名和表达式联系起来。

赋值运算符 ​​=​​。

常量

Python 中可以直接使用常量。

print(322)
print(5.3)
print("Hello World")

变量

Python 中的变量不需要用关键字声明,可以直接赋值。

x = 12.2    
y = 14

变量命名规则
  • 必须以字母或下划线​​_​​ 开头
  • 必须由字母、数字和下划线组成
  • Python 区分大小写

语句

x = 2 # 赋值语句
x = x + 2 # 赋值表达式
print(x) # print 语句

使用 ​​=​​ 把值赋值给某一个变量。赋值运算符是从右开始计算的。

环境图

环境图用于显示变量和其数值之间的对应关系。

表达式

表达式描述了一次计算和取值。

所有的表达式都可以通过函数表达式实现。

例如:​​max(1,2)​​ 这样的称为调用表达式(call expression),它的结构如下:

add        (2    ,     3)
operator operand operand

操作符和操作数也是表达式。

数字表达式

使用 ​​+, -, *, /, **, %​​ 做数学运算,其中 ​​**​​ 是幂运算。

print(4 ** 3) # 64

运算符的优先级

  • 括号最高​​()​
  • 幂运算​​**​
  • 乘法、除法、求余​​* / %​
  • 加法、减法​​+ -​
  • 从左到右​​from left to right​

逻辑运算符

  • ​not​​ 为非运算符,类似其他语言的​​!​
  • ​and​​ 为与运算符,类似其他语言的​​&&​
  • ​or​​ 为或运算符,类似其它语言的​​||​

三元运算符

Python 中的三元运算符和其他编程语言不同: ​​condition ? x : y​​,而是 ​​result = x if condition else y​​。

类型

Python 的变量、常量、字面量都有类型。

有些运算是禁止的,例如:1 + string。

可以使用 ​​type()​​ 找出某个数据的类型。

Python 中有隐式类型转换。

type(1)
# <class'int'>

数字

主要有 ​​int, float, double​​ 类型。

Python 中整数的除法结果是浮点数。

字符串转化

可以使用 ​​int(),float()​​,可以把字符串变成整数。如果字符串中不包含数字,那么会得到 ​​error​​。

字符串

Python 可以使用单引号 ​​''​​ 或者双引号 ​​""​​ 来表示字符串。

字符串包含数字,仍然是字符串。

字符串是不可变的(immutable)。例如:

s = "hello"
s[0] = 'y' # error
s = 'y' + s[1:len(s)] # 可以,因为 s 现在是一个新对象
s = "yello" # 可以

字符数字转换

可以使用 ​​int()​​ 把字符串转化为数字。

可以使用 ​​str()​​ 把数字转化为字符串。

通常使用字符串来接收输入,然后再转化为想要的类型。

Python 3 中所有的字符串编码都是 Unicode。

字符串索引

可以使用 ​​[]​​ 来获取字符串中某个位置的字符。索引从 ​​0​​ 开始。

在 Python 中可以使用负值作为索引,最后一个元素的索引为 ​​-1​​,随着负值的减小,也就是绝对值的增大,实际上相当于从右往左访问字符串。

fruit = 'app'
letter = fruit[0]
print(letter) # a
print(fruit[9]) # error
print(fruit[-1]) # p

字符串长度

使用 ​​len()​​ 获得字符串的长度。

fruit = 'banana'
x = len(fruit)
print(x) # 6

字符串循环

下面两段代码是一样的效果,第二种更 Python。

s = "abcdef"
for index in range(len(s)):
if s[index] == 'i' or s[index] == 'u':
print("there is i or u")


for char in s:
if char == 'i' or char == 'u':
print("there is i or u")

可以使用 for 或 while 循环。

fruit = 'banana'
index = 0
while index < len(fruit):
letter = fruit(index)
print(letter)
index = index + 1


for letter in fruit:
print(letter)

字符串切片

使用 ​​:​​ 运算符(colon operator)完成字符串的切片操作。

切片运算符 ​​[start:stop:step]​

第一个数字是切片的开始位置,第二个数字是指切片的结束位置(直到但不包含该位置),第三个数字代表步长(默认为 1)。

如果省略第一或第二个数字,只留下冒号,那么默认从头或到尾。

s = 'Monty Python'
print(s[0:4]) # Mont
print(s[8:]) # thon
print(s[:2]) # Mo
print(s[:]) # Monty Python

s = "abcdefgh"
s[3:6] # "def" 和 s[3:6:1] 相同
s[3:6:2] # "df"
s[::] # "abcdefgh" 和 s[0:len(s):1] 相同
s[::-1] # "hgfedbca" 和 s[-1:-(len(s)+1):-1] 相同,相当于反转字符串
s[4:1:-1] # "ec"

字符串拼接

使用 ​​+​​ 连接(concatenate)字符串。

hello = "hello"
world = "world"
print(hello + world)
# helloworld

检测子串

使用 ​​in​​ 作为逻辑运算符。可以检测一个字符串是否被包含在另一个字符串中,返回一个布尔值。

fruit = 'banana'
'n' in fruit # True
'm' in fruit # False

字符串比较

使用比较运算符比较字符串。

if word == 'banana':
print("all right")

if word < 'banana':
print('your word' + word + ', coes before banana')

字符串重复

使用 ​​*​​ 运算符来对字符串重复。

silly = "hello" * 3
print(silly)
# hellohellohello

字符串库

使用字符串库中的函数,这些函数不会改变原本的字符串,而是返回一个新字符串。

使用 ​​type()​​ 查看字符串类型,类似 JavaScript 的 ​​typeof​​ ,​​dir()​​ 可以查看能够用在字符串上的所有方法。

s = ""
type(s)
>>> <type 'str'>

使用 ​​find()​​ 查找字符串的子串,它查找子串第一次出现的位置,如果没有找到返回 ​​-1​​,类似 JavaScript 的 ​​indexOf()​

fruit = 'banana'
pos = fruit.find('na')
print(pos) # 2

使用 ​​lower(), upper()​​ 把字符串转化为小写或者大写,类似 JavaScript 的 ​​toUpperCase(), toLowerCase()​

great = 'Hello World'
zap = great.lower()
print(zap) # hello world

使用 ​​replace()​​ 意思是查找并替换,它会替换所有查找到的子串。

great = 'hello bob'
nstr = great.replace('bob', 'jane')
print(nstr) # hello jane
nstr = great.replace('o', 'x')
print(nstr) # hellx bxb

使用 ​​lstrip()​​ 或 ​​rstrip()​​ 来移除左边或者右边的空白,​​strip()​​ 移除所有空白。

greet = '   hello bob   '
greet.lstrip() # 'hello bob '
greet.rstrip() # ' hello bob'
greet.strip() # 'hello bob'

使用 ​​startswith()​​ 来判断字符串前缀。

line = 'please have a nice day'
line.startswith('please') # True

​split()​​ 方法把一个字符串分割成一个字符串列表。

如果没有指定分割符,默认采用空格作为分隔符。

abc = 'with three words'
stuff = abc.split()
print(stuff)
['with', 'three', 'words']
print(len(stuff))
# 3

line = 'first:second:third'
thing = line.split()
print(thing)
# ['first:second:third']
print(len(thing))
# 1
thing = line.split(":")
print(thing)
# ['first','second','third']

两次切片

words = 'His e-mail is q-lar@freecodecamp.org'
pieces = words.split()
parts = pieces[3].split('-')
n = parts[1]
# lar@freecodecamp.org

输入输出

输入

使用 ​​input()​​ 获得用户输入,该函数返回一个字符串。

name = input('Who are you')
print('welcome', name)

输入的转化

如果想读一个数字,那么必须把获取的字符串转化为数字。

inp = input('Europe floor')
usf = int(inp)
# usf = float(inp)
print('US floor', usf)

输出

使用 ​​print()​​ 输出。使用 ​​,​​ 可以在值中间添加空格。如果使用 ​​+​​ 需要保证两端都是字符串。

x = 1
print(x)
x_str = str(x)
print(x)
print("my fav num is", x, ".", "x = ", x)
print("my fav num is" + x_str + ". " + "x = " + x_str)

注释

Python 使用 ​​#​​ 来注释单行语句。

使用 ​​''''''​​ 注释多行语句。

# 注释

'''
注释
'''

Python 脚本

Python 的文件以 ​​.py​​ 结尾。

运行 Python 文件使用命令:

python file.py

缩进

  • 缩进(indentation)出现在​​if​​ 语句或者​​for​​ 语句等之后的​​:​
  • 使用缩进来指示作用域
  • 当​​if​​ 或​​for​​ 语句结束时要把缩进返回到上一级
  • 空行会被忽略,它们不会影响缩进
  • 注释同样会被忽略

注:Python 检查缩进的正确性,所以不要弄混 ​​space​​ 和 ​​tab​

条件

x = 5
if x < 10:
print("smaller")
if x > 20:
print("bigger")
print("Finis")

比较运算符

比较运算符:​​<, <=, ==, >=, >, !=​​。

比较运算符常用在布尔表达式中,返回真或假。

比较运算符不会改变变量的值。

if else

x = 4
if x > 2:
print("bigger")
else:
print("smaller")
print 'all done'

if elif else

if x < 2:
print("small")
elif x < 10:
print("meduim")
else:
print("large")
print("all done")

为“True”的条件

a = True

if a is True:
print("True")

if a == True:
print("True")

if a:
print("True")

if bool(a):
print("True")

# 以上四种结果皆为 True

以上四种判断的相同点:

  • 结果均为 True

不同点:

  • 第一种是判断 a 是否为 True,如果是 True 之外的任何一个值,都不会通过条件判断。
    这种做法适合于把 True 单独拿出来作为一种情况。
    a is True 的反面不是 a is False,而是 a is not True。
  • 第二种实际上不太应该出现。
    == 运算符在 Python 中会被重载,所以判断是不是 True 本人,应该用第一种做法。
  • 第三种适合于非常确定 a 的类型的情况。
  • 第四种中 bool 是一个 Class,这种写法和第三种没有什么区别。

循环

while

n = 5
while n > 0:
print(n)
n = n - 1
print("blasoff")

使用 ​​break​​ 语句可以结束并跳出当前循环。

while True:
line = input('>')
if line == 'done':
break
print(line)
print('done')

使用 ​​break​​ 语句可以结束当前循环并回到循环顶部。

while True:
line = input('> ')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print('done!')

for

for range

有些循环的次数是确定的:

for n in range(5):
print(n)
# 0 1 2 3 4

注意从 0 开始,然后到 range 内的值减 1。

range 函数签名:​​range(start, stop, step)​​,其中 start 代表迭代开始的数字,stop 代表结束的数字 + 1,step 代表迭代的步长。参数必须是整数。如果是倒序循环,步长为 ​​-1​

for i in range(1,4):
print(i)
# 1,2,3

for i in range(1,4,2):
print(i)
# 1,3

for in

例如 ​​for in​​ 循环可以迭代集合全部元素,类似 JavaScript 的 ​​forEach()​​。

for i in [1,2,3,4,5]:
print(i)
print('blase off')
# 1,2,3,4,5

friends = ['tom','cat']
for friend in friends:
print('happy:', friend)
print('done')
# happy: tom
# happy: cat
# done

上面例子中的:​​i​​ 和 ​​friend​​ 被称为迭代变量,用来迭代列表。每次只会执行一次。

更“聪明”的循环:

找出列表中的最大数字:

largest_so_far = -1
print("before", largest_so_far)
for the_num in [1,2,3,45,6]:
if the_num > largest_so_far:
largest_so_far = the_num
print(largest_so_far, the_num)

print('after', largest_so_far) # 74

计数循环:

zork = 0
print('before', zork)
for thing in [1,2,3,4,5]:
zork = zork + 1
print(zork, thing)
print('after', zork)

计算总和:

zork = 0
print('before', zork)
for thing in [1,2,3,4,5]:
zork = zork + thing
print(zork, thing)
print('after', zork)

平均数:

count = 0
sum = 0
for value in [1,2,3,4,5]:
count = count + 1
sum = sum + value
print('average', sum / count)

使用布尔值查找变量:

found = False
for value in [1,2,3,4,5]:
if value == 3:
found = True
print(found)

函数

定义

函数是保存并重复使用的代码段,它接收参数, 做运算,并返回结果。

直到程序调用(called)或者引用(invoked)函数才会运行。

特点

  • 有函数名
  • 有参数(0 或多个)
  • 有注释(docstring)(可选但是推荐)
  • 有函数体
  • 有返回值

编写和调用

使用 ​​def​​ 关键字去定义函数。

通过函数名来调用函数。

Python 中有两种函数:

  1. 内置函数是 Python 语言提供的
  2. 自定义的函数

​return​​ 语句会结束函数执行,并返回函数的结果。

如果没有指定 return 语句, Python 会返回 ​​None​​。

实参(actual parameter),形参(formal parameter),参数可以是函数类型的。

函数签名指明了函数接受参数的个数,函数签名含有所有创造局部作用域的信息。

def <name>(<formal parameters>):
return <return expression>

def fun_a():
print("this is a")

print fun_a() # None

下面是一个例子:

def is_even(i):
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
print("inside is_even")
return i % 2 == 0

is_even(3)

def thing():
print('hello')
print('fun')
thing()
print('zip')
thing()

def great(lang):
if lang == 'es':
print('hola')
elif lang == 'fr':
print('bonjour')
else:
print('hello')

作用域

有全局作用域和局部作用域两种。

  • 在函数内部,可以访问外部定义的变量
  • 在函数内部,不能改变外部定义的变量 -- 可以使用全局变量

# example1
def f(y):
x = 1
x += 1
print(x)

x = 5
f(x)
print(x)

# example2
def g(y):
print(x)
print(x + 1)

x = 5
g(5)
print(x)

# example3
def h(y):
x += 1

x = 5
h(x)
print(x)
# unboundLocalError

列表

定义

列表是一种集合。有许多值存在一个变量中。

friends = ['wu', 'niu', 'su']

列表常量是指用户用方括号 ​​[]​​ 包围的一组元素,元素之间用逗号分割。

列表的元素可以是任何 Python 对象,甚至是另一个列表(广义表)。

列表可以为空。

l = []
c = ['code', 42]
a = [3, [2,1], 3]

访问

可以使用方括号实现索引访问列表。

code = ['code','apple']
print(code[0]) # code

列表是可变的(mutable),可以使用索引操作符修改列表元素,仍然是一个对象。字符串是不可变的,必须在一个新的字符串上做修改。

c = ['code', 42]
c[0] = 1
print(c) # [1, 42]

迭代

列表可以被迭代,下面是两种常用的模式。

注:

  • 索引从​​0​​ 到​​len(l) - 1​
  • range(n) 从​​0​​ 到​​n-1​

# example1
total = 0
for i in range(len(l)):
total += l[i]
print total

# example2
total = 0
for i in l:
total += i
print total

拼接

使用 ​​+​​ 拼接列表,原来的列表不会被改变。

a = [1,2,3]
b = [4,5,6]
c = a + b
print(c) #[1,2,3,4,5,6]

切片

使用 ​​:​​ 对列表做切片。

t = [1,2,3,4,5]
t[1:4] #2,3,4

type() & dir()

使用 ​​type()​​ 查看列表类型,​​dir()​​ 可以查看能够用在列表上的所有方法。

<type 'list'>

添加

使用 ​​append()​​ 方法添加元素到列表末尾。

stuff = list()
stuff.append('book')
stuff.append('cookie')

删除

使用 ​​del(L[index])​​ 可以删除一个给定索引的元素。

使用 ​​pop()​​ 删除列表的末尾元素,并返回被删除的元素。

使用 ​​L.remove(element)​​ 删除一个给定元素。

  • 先找到元素并删除
  • 如果该元素出现了多次,只删除第一个
  • 如果列表没有该元素,给出错误

L = [2,1,3]
L.remove(2) # L = [1,3]
del(L[0]) # L = [3]
L.pop() # return 3 && L = []

in & not in

使用 ​​in, not in​​ 判断某元素是否在一个列表,返回一个布尔值。

t = [1,2,3,4,5]
1 in t
# True
8 not in t
# True

排序、反转

使用 ​​sort()​​ 和 ​​sorted()​​ 对列表排序。

​sorted()​​ 不会改变原列表,返回一个排序列表。

​sort()​​ 排序原列表。

​reverse()​​ 反转列表。

t = [1,3,2,4,5]
t.sort() # t = [1,2,3,4,5]
t.sorted() # return [1,2,3,4,5] t = [1,3,2,4,5]
t.reverse() # t = [5,4,2,3,1]

len(),max(),min(),sum()

​len(),max(),min(),sum()​​等方法把列表作为参数。

列表字符串互转

使用 ​​list(s)​​ 把字符串转化为列表,返回一个列表带有字符串中的每个字符。

使用 ​​s.split() ​​ 分割一个字符串根据指定参数,如果没有参数则以空格分割。

使用 ```.join(L)` 把字符列表转化字符串。引号里的内容是每个元素间的分隔符。

s = "I<3 cs"
list(s) # ['I', '<', '3', ' ', 'c', 's']
s.split('<') # ['I', '3 cs']

L = ['a','b','c']
''.join(L) # "abc"
'_'.join(L) #a_b_c

克隆

使用 ​​[:]​​ 克隆一个列表(创建一个新列表,并拷贝所有元素)

cool = ['blue']
chill = cool[:]
chill.append('black')
print(chill) # ['blue','black']
print(cool) # ['blue']

字典

定义

字典(dictionary)是多个值的“背包”,每个值都有一个标签,类似于键值对,哈希表数据结构,JavaScript 对象,Java 属性或者 Map 或 HashMap。

字典字面量(常量)使用花括号 ​​{}​​ 来表示一个键值对组。也可以使用花括号来创建空字典。

字典的值可以是任何类型,但是键必须是唯一的,而且必须是不可变的,也就是 float、tuple、int、string、boolean。

jjj = {'chuck': 1, 'fred': 43, 'jan': 100}
print(jjj)
# {'chuck': 1, 'fred': 43, 'jan': 100}
ooo = {}
print(ooo)
# {}

访问

字典是无序的,所以不能用位置也就是数字索引访问,需要标签,也就是字符索引。

purse = dict()
purse['money'] = 12
purse['candy'] = 12
print(purse)
# ['money': 12, 'candy': 12]
purse['candy'] = purse['candy'] + 2
print(purse)
# ['money': 12, 'candy': 14]

如果访问一个不存在的键,Python 会给 error。

添加删除

使用 ​​[] =​​ 来添加一个键值对。

grades['Sylvan'] = 'A'

使用 ​​del()​​ 删除一个键值对。

del(grades['Ana'])

in

可以使用 ​​in​​ 操作符访问键是否在字典中。

ccc = dict()
print(ccc['csev'])
# Traceback ...
'csev' in ccc
# False

如果发现了一个新名字,加入字典,随后再发现,就叠加字典的值

counts = dict()
names = ['csev','cwen']
for name in names:
if name not in counts:
counts[name] = 1
else:
counts[name] = counts[name] + 1
print(counts)

get

​get()​​ 方法检查字典中是否已经存在一个键,如果不存在会给该键设定一个默认值。

if name in counts:
x = counts[name]
else:
x = 0

# 上面 4 行和下面 1 行相同

x = counts.get(name, 0)

计算文本中每行的字数需要分割行为单词,然后循环单词列表,并用字典去跟踪每个单词。

counts = dict()
print('enter a line of text: ')
line = input('')

words = line.split()

print("words: "+ words)

print("counting...")
for word in words:
counts[word] = counts.get(word,0) + 1
print('counts', counts)

尽管字典是无序的,但是仍然可以使用 ​​for​​ 循环去迭代字典的键。

counts = {'chuck': 1, 'fred': 43, 'jan': 100}
for key in counts:
print(key, counts[key])

# chuck 1
# fred 43
# jan 100

list()、.keys()、.items()

使用 ​​list()​​ 把字典的键转化为列表。

使用 ​​.keys()​​ 得到字典的键的列表, 使用 ​​values()​​ 得到字典值的列表,使用 ​​.items()​​ 得到字典键值对的元组。

jjj = {'chuck': 1, 'fred': 43, 'jan': 100}
print(list(jjj))
# ['chunk','fred','jan']
print(jjj.keys())
# ['chunk','fred','jan']
print(jjj.values())
# [1,43,100]
print(jjj.items())
# [('chuck', 1), ('fred', 43), ('jan', 100)]

双迭代变量,可以直接输出键值对。

jjj = {'chuck': 1, 'fred': 43, 'jan': 100}
for aaa,bbb in jjj.items():
print(aaa, bbb)

# chuck 1
# fred 43
# jan 100

双重循环

bigcount = None
bigword = None
for word.count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)

元组

定义

元组(tuple)类似于列表,索引也是从 ​​0​​ 开始。

元组可以包含整型、浮点型、字符串等。

使用括号(parentheses) ​​()​​ 来表示元组。

te = ()

t = (2, "mit", 3)

x = ('Glenn', 'Sally')
print(x[1])
# Sally

y = (1, 2, 3)
print(y[1])
# 2
print(max(y))
# 3

for item in y:
print(item)
# 1
# 2
# 3

元组和列表的区别是,元组是不能改变的(immutable),这类似于字符串。

元组中不能做的事

  • 元组对象不能被排序(sort())
  • 元组对象不能添加(append())
  • 元组对象不能被翻转(reverse())

元组只有 ​​count​​ 和 ​​index​​ 属性。

拼接元组

使用 ​​+​​ 可以拼接元组

(2, "mit", 3) + (5, 6)
# (2, "mit", 3, 5, 6)

元组切片

使用 ​​[:]​​ 可以对元组切片。

t[1:2] # ("mit", )
t[1:3] # ("mit", 3)

注意第一个例子的 ​​,​​ 不是错误,而是 Python 表示这是一个元组,否则就变成了字符串。

元组大小

使用 ​​len()​​ 得到元组大小。

便捷的交换操作

(x, y) = (y, x)

赋值

可以把元组放在赋值运算符的左侧,甚至可以忽略括号。

(x, y) = (4, 'fred')
print(y) # fred
(a, b) = (99, 98)
print(a) # 99

比较

元组是可以比较的。如果第一个元素相同,会继续比较。

(0, 1, 2) < (5, 1, 2)
# True
(0, 1, 20000) < (0, 3, 4)
# True

迭代

元组可以被迭代。

排序

可以使用 ​​sorted()​​ 对元组列表排序。

d = ['a': 10, 'b': 10, 'c': 10]
d.items()
sorted(d.items())

按值排序:

d = ['a': 10, 'b': 20, 'c': 30]
tmp = list()
for k,v in c.items():
tmp.append((v, k))
print(tmp)
# [(10, 'a'), (30, 'c'), (20, 'b')]
tmp = sorted(tem, reverse=True)
print(tmp)
# # [(30, 'c'), (20, 'b'), (10, 'a')]

更短的版本:

print(sorted([(v, k) for k,v in c.items() ]))

别名

所有的别名(alias)指向同一对象,所以对其中一个更改,其他的也会更改。

a = 1
b = a
print(a) # 1
print(b) # 1

warm = ['red', 'yellow', 'orange']
hot = warm
hot.append('pink')
print(hot) # ['red', 'yellow', 'orange', 'pink']
print(warm) # ['red', 'yellow', 'orange', 'pink']

断言

断言(assertion)用来判断预期和实际结果相同。

def avg(grades):
assert not len(grades) == 0, 'no grades data'
return sum(grades)/len(grades)

如果是空列表,给出 AssertionError,其他情况 ok。

异常

try except

异常使用 ​​try/except​​ 结构。

  • 对于一段“危险”代码,应该使用异常处理
  • 如果​​try​​ 中的代码可以工作,那么​​except​​ 的部分会被跳过
  • 如果​​try​​ 中的代码不能工作,那么会跳转到​​except​​ 的部分

name = 'Bob'
try:
print('hello')
istr = int(name)
print('there')
except:
istr = -1
print('done', istr)

使用多个 except 语句处理某种特殊情况的异常

try:
...
except ValueError:
...
except ZeroDivisionError:
...
except:
...

else & finally

else 在 try 中语句没问题时运行,finally 无论 try 中语句是否有错误都会执行。

raise

当出现错误时,显示错误条件。

在 Python 中,抛出一个 exception 使用 ​​raise​​。

格式:​​raise <exceptionName>(<arguments>)​

raise Exception("descriptive string")

面向对象编程

class & object

​class​​ 是类的关键字,​​object​​ 类是 Animal 的父类,​​__init__​​ 是创建实例的方法(注意双下划线 double underscore),​​self​​ 代表该类的一个实例。

类中的数据成员和方法成员需要缩进。

class Animal(object):
def __init__(self, age):
self.age = age
self.name = None

myAnimal = Animal(3)

不用给 ​​self​​ 提供参数,Python 会自动完成。

两种等价写法:

# 传统方法
c = Coordinate(3,4)
zero = Coordiante(0,0)
print(c.distance(zero))

# 等价写法
c = Coordinate(3,4)
zero = Coordinate(0,0)
print(Coordinate.distance(c,zero))

打印一个对象

c = Coordiante(3,4)
print(c)
<__main__.Coordinate object at 0x7..>

  • 默认是不详细的(uninformative)打印表示
  • 为一个类定义一个__str__ 方法
  • 当打印一个对象时,Python 调用__str__ 方法
  • 例如打印 <Coordinate.x , Cooridnate.y>

class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.x)**2
return (x_diff_sq + y_diff_sq) ** 0.5
def __str__(self):
return "<"+str(self.x)+","+str(self.y)+">"

类型 & isinstance()

print(type(c))
# <class __main__.Coordiante> c 的类型是 Coordinate 类
print(Coordinate)
# <class __main__.Coordiante> Coordinate 是一个类
print(type(Coordinate))
# <type 'type'> Coordinate 也是一种对象

使用 ​​isinstance()​​ 查看某个变量是否为一个类的实例

print(isinstance(c, Coordinate))
# True

其它方法

__add__(self, other) # self + other
__sub__(self, other) # self - other
__eq__(self, other) # self == other
__lt__(self, other) # self < other
__len__(self, other) # len(self)
__str__(self, other) # print self

getter & setter

getter 用来返回类的属性,setter 用来设置类的属性。

class Animal(object):
def __init__(self, age):
self.age = age
self.name = None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self, newAge):
self.age = newAge
def set_name(self, newName=""):
self.name = newName
def __str__(self):
return "animal:" + str(self.name) + ":" + str(self.age)

dot natation

用 ​​.​​ 来访问属性(数据和方法)。

a.age
a.get_age()

Python 在信息隐藏方面的缺陷

以下行为都是不推荐的:

  • Python 允许在类定义外访问数据

print(a.age)

  • Python 允许在类定义外修改数据

a.age = 'infinite'

  • Python 允许在类定义外为一个实例创建属性

a.size = "tiny"

默认参数

如果没有给定实参,那么给形参的默认参数会启用。

def set_name(self, newname=""):
self.name = newname

a = Animal(3)
a.set_name()
print(a.get_name()) # ""

a = Animal(3)
a.set_name("fluffy")
print(a.get_name()) # 'fluffy'

继承

子类/派生类(child class) 可以继承父类/超类/基类(parent class / super class/ base class)

class Cat(Animal):
def speak(self):
print("meow")
def __str__(self):
return "cat:" + str(self.name) + ":" + str(self.age)

Cat 可以继承所有 Animal 的属性。

class Person(Animal):
def __init__(self,name,age):
Animal.__init__(self,age) # 调用父类构造函数
self.set_name(name)
self.friends = []

类变量

class Rabbit(Animal):
tag = 1 # 类变量
def __init__(self,age,parent1=None,parent2=None):
Animal.__init__(self,age)
self.parent1 = parent1
self.parent2 = parent2
self.rid = Rabbit.tag # rid 是实例变量
Rabbit.tag += 1

tag 用来给每个 Rabbit 实例独一无二的 id。

文件

一个文本文件可以被视为一系列行。

在读文件内容之前,我们必须告诉 Python 哪个文件能够使用并且我们要怎么做。这就需要 ​​open()​​ 函数。

​open()​​ 函数返回一个“文件句柄”--一个用于文件操作的变量。

这类似于 word 中 “文件->打开”。

​handle = open(filename, mode)​​,返回一个 handle 去操作文件,文件名是字符串。mode 是可选项,但是如果读文件应该用 'r',如果写文件应该用 'w'。举例:​​fhand = open('mbox.txt', 'r')​

换行符

使用换行符 ​​\n​​ 来表示一行的结尾。

换行符是一个字符,而不是两个。

stuff = 'x\ny'
print(stuff)
# x
# y

file handle 可以被视为字符串的序列,也就是说文件中任意一行都是字符串。所以我们可以使用 ​​for​​ 语句来迭代该序列。

注:一个序列是一个有序列表

xfile = open('mobx.txt')
for cheese in xfile:
print(cheese)

计算文件的行数:

fhand = open('mbox.txt')
count = 0
for line in fhand:
count = count + 1
print('line count ', count)

读取整个文件:

把文件的整个内容带着换行符一起读取

fhand = open('xx.txt')
inp = fhand.read()
print(len(inp))

过滤读取:

xfile = open('mobx.txt')
for cheese in xfile:
cheese = cheese.rstrip()
if cheese startswith('from'):
print(cheese)

读取不同的文件:

fname = input('enter file name: ')
fhand = open(fanme)
count = 0
for line in fhand:
if line startswith('sub'):
count = count + 1
print('there are ', count, 'subject lines in ', fname)

正则表达式

Python 中使用正则表达式需要导入包:

import re

使用 ​​re.search()​​ 来查看字符串是否匹配正则表达式,类似于使用 ​​find()​​ 在字符串中,返回一个布尔值,取决于是否匹配到了。

可以使用 ​​re.findall()​​ 去提取字符串和正则匹配的部分,返回一个列表,包含匹配的子串。

hand = open('xx.txt')
for line in hand:
line = line.rstrip()
if line.find('From') >= 0:
print(line)

import re
hand = open('xx.txt')
for line in hand:
line = line.rstrip()
if re.search('From', line):
print(line)

和 ​​startswith()​​ 相同,使用 ​​^​

import re
hand = open('xx.txt')
for line in hand:
line = line.rstrip()
if re.search('^From', line):
print(line)

​.​​ 匹配任何字符。​​*​​ 匹配任何次数。​​+​​ 一个或更多。

​:​​ 最后一个匹配的字符

y = re.findall('[0-9]+', x)
print(y)

贪婪匹配会匹配最后一个出现的匹配。

非贪婪匹配会匹配第一个出现的匹配,使用 ​​?​​。

网络

Sockets

Python 有内置的 TCP Sockets 支持

import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\n\n'.encode()
mysock.send(cmd)

while True:
data = mysock.recv(512)
if (len(data) < 1):
break
print(data.decode())
mysock.close()

字符串转字节

使用 ​​.decode()​​ 方法。

import socket

while True:
data = mysock.recv(512)
if (len(data) < 1):
break
mystring - data.decode()
print(mystring)

使用 urllib

urllib 是一个库

import urllib.request, urllib.parse, urllib.error

fhand = urllib.request.urlopen('http://data.pr4e.org/remeo.txt')
for line in fhand:
print(line.decode().strip())

Web 服务

有两种主流的数据交换格式:XML 和 JSON。

XML 和 XML Schema:

<person>
<lastname>Severance</lastname>
<age>17</age>
<dateborn>2001-01-17</dateborn>
</person>

<xs:complexType name="person">
<xs:sequence>
<xs:element name="lastname" type="xs:string" />
<xs:element name="age" type="xs:integer" />
<xs:element name="dateborn" type="xs:date" />
</xs:sequence>
</xs:complexType>

JSON(JavaScript Object Notation):

import json
data = '''{
"name": "Chunk",
"phone": {
"type": "intl",
"number": "fsd"
},
"email": {
"hide": "yes"
}
}'''

info = json.loads(data)
print('Name:', info["name"])

Set

​set​​ 是一种保存不重复数据的结构。

使用 ​​set()​​ 构造一个 set,可以传入一个列表并去掉重复元素。

li = [1,2,3,1]
sets = set(li) // [1,2,3]
len(sets) // 3

举报

相关推荐

python 笔记

python笔记

Python笔记

Python笔记09

Python笔记08

Python自学笔记

0 条评论