1.条件语句
#1 if elif else
score = 55
if score > 80:
print("优秀")
elif score > 60:
print("及格")
else:
print("未及格")
#2 条件表达式
result = "及格" if score>60 else "未及格"
print(result) # 未及格
2.循环语句
# for循环
for i in range(5):
print(i, end=' ') # 0 1 2 3 4
print('
')
# while循环
i = 0
while i < 5:
print(i, end=' ') # 0 1 2 3 4
i += 1
print('
')
# break语句
for i in range(5):
if i > 2:
break
print(i, end=' ') # 0 1 2
print('
')
# continue语句
for i in range(5):
if i % 2 == 0:
continue
print(i, end=' ') # 1 3
print('
')
# for/else语句
for i in range(5):
if i > 10:
break
print(i, end=' ') # 0 1 2 3 4
else:
# else块在循环正常结束时执行
print("我执行了")
3.函数
#1 函数定义与调用
def func(name, age=20, *args, **kw):
print(name, age)
print(args)
print(kw)
func('Mary', 21, 1,2, a='A',b='B')
# Mary 21
# (1, 2)
# {'a': 'A', 'b': 'B'}
#2 lambda匿名函数
add = lambda x, y: x + y
print(add(2,3)) # 5
# 在定义时绑定值
y = 10
add = lambda x, y=y: x + y
print(add(2)) # 12
funcs = [lambda x: x+n for n in range(5)]
for func in funcs:
print(func(5)) # 9 9 9 9 9
# 在定义时绑定值
funcs = [lambda x, n=n: x+n for n in range(5)]
for func in funcs:
print(func(5)) # 5 6 7 8 9
#3 偏函数
from functools import partial
int2 = partial(int, base=2)
print(int2('110')) # 6
max10 = partial(max, 10) # 把10加入比较
print(max10(1,2,3)) # 10
#4 命令行参数
import sys
print(sys.argv[0])
print(sys.argv[1])
4.异常
#1 捕获异常
try:
print(int('100years'))
except ValueError as e:
print('ValueError:', e)
else:
# try语句没有异常时执行
print('No error!')
finally:
# 此处代码一定会执行
print('Finally...')
#2 捕获多个异常
try:
file = open('file.txt', 'rb')
except EOFError as e:
print("An EOF error occurred.")
raise e
except IOError as e:
print("An error occurred.")
raise e
#3 捕获所有异常
try:
file = open('file.txt', 'rb')
except Exception as e:
raise e
5.测试
# test.py
import unittest
class TestList(unittest.TestCase):
# 测试方法以test开头
def test_pop(self):
l = [1, 2, 3]
r = l.pop()
self.assertEqual(l, [1,2])
self.assertTrue(r == 3)
self.assertFalse(r == 1)
def test_index(self):
l = [1, 2, 3]
n = l.index(2)
self.assertEqual(n, 1)
with self.assertRaises(ValueError):
n = l.index(4)
if __name__ == '__main__':
unittest.main()
# python test.py -v
6.文件处理
读取文件
#1 读取文本文件
f = open('a.txt', 'r', encoding='gbk')
data = f.read()
print(data)
f.close()
with open('test.txt', 'r') as f:
# 读取文件全部内容,返回str
print(f.read())
with open('test.txt', 'r') as f:
# 每次最多读取6个字节的内容,返回str
print(f.read(6))
with open('test.txt', 'r') as f:
# 每次读取一行内容,返回str
print(f.readline())
with open('test.txt', 'r') as f:
# 读取文件全部内容,按行返回list
print(f.readlines())
#2 读取二进制文件
with open('test.bin', 'rb') as f:
data = f.read(16)
text = data.decode('utf-8')
写入文件
#1 写入文本文件
with open('test1.txt', 'w') as f:
f.write('Hello, world!')
#2 将print输出重定向到文件
with open('test2.txt', 'wt') as f:
print('Hello World!', file=f)
#3 写入二进制文件
with open('text3.bin', 'wb') as f:
text = 'Hello World'
f.write(text.encode('utf-8'))
os
import os
os.name # 操作系统类型
os.environ # 操作系统中的环境变量
os.getcwd() # 当前工作目录
os.listdir('.') # 列举目录的文件
os.stat('a.txt') # 获取文件元数据
os.rename('a.txt', 'a.py') # 重命名
os.remove('a.txt') # 删除文件
os.mkdir('test') # 创建目录
os.chdir('test') # 切换目录
os.makedirs('dir1/dir2') # 创建多级目录
# 递归遍历文件夹
for root, dirs, files in os.walk('.'):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
os.path
import os
os.path.abspath('.') # 查看绝对路径
os.path.exists('.') # 文件或目录是否存在
os.path.isdir('.') # 是否是目录
os.path.isfile('.') # 是否是文件
os.path.islink('.') # 是否是链接
os.path.realpath('.') # 返回被链接的原始文件
os.path.getsize('a.txt') # 获取文件大小
os.path.getmtime('a.txt') # 获取修改日期
# 目录合并
print(os.path.join('test', 'test.txt'))
# test/test.txt
# 目录分离
path = '/home/test/test.txt'
print(os.path.basename(path)) #'test.txt'
print(os.path.dirname(path)) #'/home/test'
print(os.path.split(path))
#('/home/test', 'test.txt')
print(os.path.splitext(path))
#('/home/test/test', '.txt')
7.迭代器
迭代器实现
class Fib(object):
def __init__(self, num):
self.a, self.b = 0, 1
self.num = num
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > self.num:
raise StopIteration()
return self.a
fib = Fib(10)
for i in fib:
print(i) # 1 1 2 3 5 8
import itertools
#1 count(1)从1开始创建一个无限的迭代器
num = itertools.count(1)
for i in num:
if i > 5:
break
print(i, end=' ') # 1 2 3 4 5
#2 cycle()把传入的序列无限重复下去
alpha = itertools.cycle('ABC')
n = 0
for i in alpha:
if n > 6:
break
n += 1
print(i, end=' ') # A B C A B C A
#3 repeat()把一个元素无限重复下去,第二个参数可以限定重复次数
alpha = itertools.repeat('A', 3)
for i in alpha:
print(i, end=' ') # A A A
#4 takewhile()根据条件截取出一个有限的序列
num = itertools.count(1)
part = itertools.takewhile(lambda x: x < 5, num)
print(list(part)) # [1, 2, 3, 4]
#5 chain()把一组迭代对象连接起来
for i in itertools.chain('ABC', 'DEF'):
print(i, end=' ') # A B C D E F
#6 groupby()把迭代器中相邻的重复元素挑出来放在一起
for key, group in itertools.groupby('ABBCCC'):
print(key, list(group))
# A ['A']
# B ['B', 'B']
# C ['C', 'C', 'C']
#7 groupby()的挑选规则通过函数完成,只要作用于函数的两个元素的返回值相等,就被认为是一组,而函数返回值作为组的key
for key, group in itertools.groupby('AaBBbcCcC', lambda c: c.upper()):
print(key, list(group))
# A ['A', 'a']
# B ['B', 'B', 'b']
# C ['c', 'C', 'c', 'C']
8.生成器
#1 使用推导式构建生成器
g = (x * x for x in range(5))
for i in g:
print(i) # 0 1 4 9 16
#2 使用yield关键字构建生成器
def g():
for i in range(5):
yield i * i
for i in g():
print(i) # 0 1 4 9 16
9.闭包
#1 闭包
def lazy_sum(*args):
def sum():
_sum = 0
for n in args:
_sum += n
return _sum
return sum
f = lazy_sum(1,2,3,4,5)
print(f()) # 15
#2 循环变量的当前值未被捕获:
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
print(f1(), f2(), f3()) # 9 9 9
#3 循环变量的当前值被捕获:
def count():
fs = []
for i in range(1, 4):
def f(_i=i):
return _i*_i
fs.append(f)
return fs
f1, f2, f3 = count()
print(f1(), f2(), f3()) # 1 4 9
#4 利用闭包实现计数器,每次调用返回递增整数:
def createCounter():
fs = [0]
def counter():
fs[0] = fs[0] + 1
return fs[0]
return counter
f = createCounter()
for i in range(5):
print(f()) # 1 2 3 4 5
10.装饰器
import functools
import time
#1 装饰器
def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print(func.__name__)
return func(*args, **kw)
return wrapper
@log
def func():
print('Hello')
func()
# func
# Hello
#2 传入参数的装饰器
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print(text, func.__name__)
return func(*args, **kw)
return wrapper
return decorator
@log('execute')
def func():
print('Hello')
func()
# execute func
# Hello
#3 打印函数的执行时间
def metric(fn):
@functools.wraps(fn)
def wrapper(*args, **kw):
start = time.time()
f = fn(*args, **kw)
print(time.time() - start)
return f
return wrapper
@metric
def func():
sum = 0
for i in range(1000000):
sum += i*i*i*i
sum -= i*i*i*i
print('sum: ', sum)
func()
# sum: 0
# 0.25935
#4 装饰器类
class logit(object):
def __init__(self, msg):
self.msg = msg
print('init:', self.msg)
def __call__(self, func):
def wrapper(*args, **kw):
print(func.__name__)
print(self.msg)
return func(*args, **kw)
return wrapper
@logit('log')
def func():
print("Hello")
func()
# init: log
# func
# log
# Hello
11.上下文管理器
#1 基于类,定义enter和exit方法
class File(object):
def __init__(self, name, method):
self.file = open(name, method)
def __enter__(self):
return self.file
#exit返回True清空处理异常,否则抛出异常
def __exit__(self, type, val, trace):
self.file.close()
return True
with File('test.py', 'r') as f:
f.undefined_function()
print('Hello') # 这里不执行了
#2 基于生成器
from contextlib import contextmanager
@contextmanager
def open_file(name):
f = open(name, 'w')
yield f
f.close()
with open_file('test.txt') as f:
f.write('hello!')
#3 首尾代码固定时:
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("</%s>" % name)
with tag("h1"):
print("hello world")
# <h1>
# hello world
# </h1>