一、条件和循环
1 | ## if条件判断 |
二、迭代器与生成器
迭代器有两个基本的方法:iter()
和 next()
。1
2
3
4
5
6
7
8
9
10list=[1,2,3,4]
it = iter(list) # 创建迭代器对象
for x in it:
print (x, end=" ")
while True:
try:
print (next(it))
except StopIteration:
sys.exit()
使用了 yield
的函数被称为生成器(generator),作用是函数执行时遇到这个关键字的时候就会停止执行,知道调用了next之后才能继续执行1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import sys
def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()
三、函数
1 | def 函数名(参数列表): |
1. 参数
- 必需参数
- 关键字参数
调用时:
printinfo( age=50, name="light" );
- 默认参数
定义时:
def printinfo( name, age = 35 ):
- 不定长参数
定义时:
def printinfo( name, *str ):
类似与java的...
- 字典
定义时:
def printinfo( name, **args):
2. 匿名函数
python 使用 lambda 来创建匿名函数。
1
2sum = lambda arg1, arg2: arg1 + arg2;
print ("相加后的值为 : ", sum( 10, 20 ))
3. global 和 nonlocal关键字
global局部变量修改全局变量的值1
2
3
4
5
6
7num = 1
def fun1():
global num # 需要使用 global 关键字声明
num = 123
print(num)
fun1()
print(num)
nonlocal关键字1
2
3
4
5
6
7
8def fun():
j = 0
def fun1():
nonlocal j
j = 5
print(j)
fun1()
print(j)
四、数据结构
1. python实现堆栈
1 | # 堆栈:先进后出,后进先出 |
2. 列表推导式和遍历
1 | vec = [2, 4, 6] |
五、模块
1 | from modname import * # 把一个模块的所有内容全都导入到当前的命名空间,但是由单一下划线(_)开头的名字不在此例。 |
每个模块都有一个__name__
属性,当其值是'__main__'
时,表明该模块自身在运行,否则是被引入。
1 | import fibo |
六、文件
1 | f = open(filename, mode) # 打开文件 |
六、错误和异常
1 |
|
预定义的清理行为
关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法1
2
3with open("myfile.txt") as f:
for line in f:
print(line, end="")
自定义异常
1 | class MyError(Exception): |
七、面向对象
1 | class A: |
八、Python3 标准库概览
操作系统接口
os模块提供了不少与操作系统相关联的函数。1
2
3
4
5
6
7
8import os
os.getcwd() # 返回当前的工作目录
os.chdir('/server/accesslogs') # 修改当前的工作目录
os.system('mkdir today') # 执行系统命令 mkdir
import shutil
shutil.copyfile('data.db', 'archive.db')
shutil.move('/build/executables', 'installdir')
建议使用 “import os” 风格而非 “from os import *”。这样可以保证随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()。
文件通配符
1 | import glob |
命令行参数
1 | import sys |
字符串正则匹配
1 | import re |
数字:import math
随机数:import random
访问 互联网
1 | ## URL访问 |
日期和时间
1 | from datetime import date |
数据压缩
1 | import zlib |
性能度量
1 | from timeit import Timer |
测试模块
1 | # 待补充...... |