代码结构、模块、包和程序
# python代码结构
# 使用#来注释
# aa
# 使用\连接
>>> alphabet = ''
>>> alphabet += 'abcdefg'
>>> alphabet += 'hijklmnop'
>>> alphabet += 'qrstuv'
>>> alphabet += 'wxyz'
或者
>>> alphabet = 'abcdefg' + \
... 'hijklmnop' + \
... 'qrstuv' + \
... 'wxyz'
2
3
4
5
6
7
8
9
10
# 使用if、elif和else进行比较
a = 1
if a == 1:
print('1')
elif a == 2:
print('2')
else:
print('假')
2
3
4
5
6
7
# python比较符
相等 ==
不等于 !=
小于 <
不大于 <=
大于 >
不小于 >=
属于 in...
2
3
4
5
6
7
# 什么是真值
下面这几个都是假,其他的都为真
布尔 False
null 类型 None
整型 0
浮点型 0.0
空字符串 ''
空列表 []
空元组 ()
空字典 {}
空集合 set()
2
3
4
5
6
7
8
9
# 使用while进行循环
a = 1
while a <= 5:
print(a)
a += 1
2
3
4
使用brek跳出循环,使用continue跳过本次,这个各个语言都一样,这里就不解释。如果 while 循环正常结束(没有使用 break 跳出),程序将进入到可选的 else 段
a = 1
while a <= 5:
print(a)
a += 1
else:
print('结束循环')
# 输出下面内容
1
2
3
4
5
结束循环
2
3
4
5
6
7
8
9
10
11
12
13
# 使用for进行迭代
支持列表,元组,字典,集合
a = [1,2,3]
for word in a:
print(word)
#输出
1
2
3
2
3
4
5
6
7
for也可以使用else
# 使用zip来进行并行迭代
days = ['Monday', 'Tuesday', 'Wednesday']
fruits = ['banana', 'orange', 'peach']
drinks = ['coffee', 'tea', 'beer']
desserts = ['tiramisu', 'ice cream', 'pie', 'pudding']
for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts):
print(day, ": drink", drink, "- eat", fruit, "- enjoy", dessert)
# 输出
Monday : drink coffee - eat banana - enjoy tiramisu
Tuesday : drink tea - eat orange - enjoy ice cream
Wednesday : drink beer - eat peach - enjoy pie
2
3
4
5
6
7
8
9
10
# 使用range()生成自然数序列
for i in range(1,5):
print(i)
# 输出
1
2
3
4
for i in range(1,10,2):
print(i)
# 输出
1
3
5
7
9
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 推导式
推导式是从一个或者多个迭代器快速简洁地创建数据结构的一种方法。它可以将循环和条 件判断结合,从而避免语法冗长的代码。会使用推导式有时可以说明你已经超过 Python 初 学者的水平。也就是说,使用推导式更像 Python 风格
# 列表推导式
一般我们可能会使用下面这样的方法来创建一个列表
>>> list(range(1, 6))
[1, 2, 3, 4, 5]
2
如果是推导式那么可以这样写
>>> [number for number in range (1,6)]
[1, 2, 3, 4, 5]
>>> [number -1 for number in range (1,6)]
[0, 1, 2, 3, 4]
2
3
4
这里其实可以这样理解
a_list = []
for number in range(1,6):
a_list.append(number)
a_list = []
for number in range(1,6):
a_list.append(number-1)
2
3
4
5
6
7
甚至可以在里面加一个判断语句
>>> [number for number in range(1,6) if number%2==1]
[1, 3, 5]
2
>>> a_list = []
>>> for number in range(1,6):
... if number % 2 == 1:
... a_list.append(number)
...
>>> a_list
[1, 3, 5]
2
3
4
5
6
7
多重循环推导式
>>> rows = range(1,4)
>>> cols = range(1,3)
>>> for row in rows:
... for col in cols:
... print(row, col)
...
1 1
1 2
2 1
2 2
3 1
3 2
2
3
4
5
6
7
8
9
10
11
12
>> rows = range(1,4)
>>> cols = range(1,3)
>>> cells = [(row, col) for row in rows for col in cols]
>>> for cell in cells:
... print(cell)
...
(1, 1)
(1, 2)
(2, 1)
(2, 2)
(3, 1)
(3, 2)
2
3
4
5
6
7
8
9
10
11
12
# 字典推导式
>>> word = 'letters'
>>> {letter: word.count(letter) for letter in word}
{'l': 1, 'e': 2, 't': 2, 'r': 1, 's': 1}
# 改进方法如下
>>> word = 'letters'
>>> letter_counts = {letter: word.count(letter) for letter in set(word)}
>>> letter_counts
{'t': 2, 'l': 1, 'e': 2, 'r': 1, 's': 1}
2
3
4
5
6
7
8
字典键的顺序和之前的例子是不同的,因为是对 set(word) 集合进行迭代的,而前面的例 子是对 word 字符串迭代。
# 集合推导式
>>> {number for number in range(1,6) if number % 3 == 1}
{1, 4}
2
# 生成器推导式
这个推导式会返回一个迭代器,我们可以使用迭代器进行遍历
>>> number_thing = (number for number in range(1, 6))
>>> for number in number_thing:
... print(number)
...
1
2
3
4
5
2
3
4
5
6
7
8
9
# 函数
def test():
print('hello')
test()
2
3
4
None 是 Python中一个特殊的值,虽然它不表示任何数据,但仍然具有重要的作用。 虽然 None 作为布尔值和 False 是一样的。
是对于 Python 来说是很重要的。你需要把 None 和不含 任何值的空数据结构区分开来。0 值的整型 / 浮点型、空字符串('')、空列表([])、 空元组((,))、空字典({})、空集合(set())都等价于 False,但是不等于 None。 现在,快速写一个函数,输出它的参数是否是None:
>>> def is_none(thing):
... if thing is None:
... print("It's None")
... elif thing:
... print("It's True")
... else:
... print("It's False")
2
3
4
5
6
7
# 位置参数
下面这个是常用的,但是我们必须要只能每个位置分别是啥意思
def menu(wine, entree, dessert):
return {'wine': wine, 'entree': entree, 'dessert': dessert}
print(menu('chardonnay', 'chicken', 'cake'))
# 输出下面的结果
{'wine': 'chardonnay', 'entree': 'chicken', 'dessert': 'cake'}
2
3
4
5
6
# 关键字参数
为了避免参数混乱,我们可以指定参数名字,顺序甚至可以相反
def menu(wine, entree, dessert):
return {'wine': wine, 'entree': entree, 'dessert': dessert}
print(menu(entree='beef', dessert='bagel', wine='bordeaux'))
2
3
4
# 指定默认参数
我们可以给函数指定一个默认参数,这样调用函数的时候可以不指定参数
def menu(wine, entree, dessert='bagel'):
return {'wine': wine, 'entree': entree, 'dessert': dessert}
print(menu(entree='beef', wine='bordeaux'))
2
3
4
# 使用*收集可变参数
给函数传入的所有参数都会以元组的形式返回
def menu(*args):
print(args)
print(args[0])
menu("1","2","3")
# 输出
('1', '2', '3')
1
2
3
4
5
6
7
8
# 使用 ** 来收集关键字参数
def menu(**args):
print(args)
print(args['a'])
menu(a='1',b='2')
# 输出
{'a': '1', 'b': '2'}
1
2
3
4
5
6
7
8
# 文档字符串
我们可以在函数体开始的部分加上一些描述,作为函数的说明,然后我们可以直接打印出来
def menu(**args):
'这个是函数的描述'
print(args)
print(menu.__doc__)
# 输出
这个是函数的描述
2
3
4
5
6
# 函数
Python 中一切都是对象,包括数字、字符串、元组、列表、字典和函数。可以作为参数被其他函数调用, 也可以从其他函数中返回值
def test():
print("hello")
def menu(call):
call()
menu(test)
# 输出hello
2
3
4
5
6
7
8
# 内部函数
def test(a,b):
def innerFun(c,d):
return c+d
return innerFun(a,b)
print(test(1,3))
# 返回4
2
3
4
5
6
7
# 闭包
闭包就是我们直接返回一个函数,比如下面这个例子,闭包会保存临时变量,我们可以直接调用函数来获取函数里面存储的变量
def test(tmp):
def inner():
return "临时变量 '%s'" % tmp
return inner
a = test('666')
b = test('777')
print(a())
print(b())
-------------
临时变量 '666'
临时变量 '777'
2
3
4
5
6
7
8
9
10
11
12
13
# 匿名函数
lambda 函数是用一个语句表达的匿名函数。可以用它来代替小的函数,比如我们这里直接进行替换
def edit_story(words, func):
for word in words:
print(func(word))
words = ["小游", "张三", "李四"]
edit_story(words, lambda word: word + "!")
-----------------
小游!
张三!
李四!
2
3
4
5
6
7
8
9
10
11
12
# 生成器
生成器是用来创建 Python 序列的一个对象。使用它可以迭代庞大的序列,且不需要在内 存中创建和存储整个序列。range其实就是一个最简单的生成器。比如下面这个计算 1到100的整数
>>> sum(range(1,101))
5050
2
# 装饰器
有时你需要在不改变源代码的情况下修改已经存在的函数。常见的例子是增加一句调试声明,以查看传入的参数。
装饰器实质上是一个函数。它把一个函数作为输入并且返回另外一个函数。在装饰器中, 通常使用下面这些 Python 技巧:
- *args 和 **kwargs
- 闭包
- 作为参数的函数
比如我们可以这样使用装饰器
# 定义一个装饰器
def document_it(func):
def new_function(*args, **kwargs):
print('Running function:', func.__name__)
print('Positional arguments:', args)
print('Keyword arguments:', kwargs)
result = func(*args, **kwargs)
print('Result:', result)
return result
return new_function
# 自己定义一个函数
def add_ints(a,b):
return a+b
# 对这个函数进行装饰
color_add_ints = document_it(add_ints)
# 调用装饰后的函数
color_add_ints(3,5)
----------
Running function: add_ints
Positional arguments: (3, 5)
Keyword arguments: {}
Result: 8
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 命名空间和作用域
一个名称在不同的使用情况下可能指代不同的事物。Python 程序有各种各样的命名空 间,它指的是在该程序段内一个特定的名称是独一无二的,它和其他同名的命名空间 是无关的。比如我们不能在函数里面修改全局的值
name = '小游'
def change():
name = '张三'
print(name)
change()
print(name)
---------
张三
小游
2
3
4
5
6
7
8
9
如果我们想修改的话,可以加上global关键词
name = '小游'
def change():
global name
name = '张三'
print(name)
change()
print(name)
----------
张三
张三
2
3
4
5
6
7
8
9
10
python提供了两个函数来获取命名空间
name = '小游'
def change():
name = '张三'
print(globals())
print(locals())
change()
----------
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000027BB93D1C88>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/CODE/Python/入门/main.py', '__cached__': None, 'name': '小游', 'change': <function change at 0x0000027BB95C63A8>}
{'name': '张三'}
2
3
4
5
6
7
8
9
名称中_ 和 __ 的用法
以两个下划线 __ 开头和结束的名称都是 Python 的保留用法。因此,在自定义的变量中不 能使用它们。选择这种命名模式是考虑到开发者一般是不会选择它们作为自己的变量的。
# 错误和异常处理
我们使用try except来处理异常
try:
1/0
except:
print("程序出现异常")
-------
try:
1/0
except:
print("程序出现异常")
2
3
4
5
6
7
8
9
当然,我们可以可以处理知道类型的错误:
a = [1,2]
try:
a[10]
except IndexError as err:
print("下标越界",err)
except Exception as err:
print("程序出现异常",err)
---------
下标越界 list index out of range
2
3
4
5
6
7
8
9
# 编写自己的异常
class myException(Exception):
pass
# 抛出异常
raise myException("错误")
---------
Traceback (most recent call last):
File "E:/CODE/Python/入门/main.py", line 4, in <module>
raise myException("错误")
__main__.myException: 错误
2
3
4
5
6
7
8
9
# Python模块、包和程序
# 命令行参数
使用sys来获取传递进来的参数
import sys
print("系统参数",sys.argv)
-----------
(base) E:\CODE\Python\入门>python main.py 测试
系统参数 ['main.py', '测试']
2
3
4
5
# 模块和import语句
# 导入其他的模块
我们先新建一个 test.py
文件,内容如下
def test():
print("测试")
2
我们在主函数里面导入这个模块
import test
test.test()
2
注意,这两个文件要在同一个目录
当然,我们也可以这样调用
from test import test
test()
2
# 使用别名
from test import test as hello
hello()
2
# 模块搜索路径
Python 会在什么地方寻找文件来导入模块?使用命名为 path 变量的存储在标准 sys 模块下的一系列目录名和 ZIP 压缩文件。你可以读取和修改这个列表。比如打印一下我的列表
import sys
for place in sys.path:
print(place)
-----------
E:\CODE\Python\入门
E:\CODE\Python\入门
D:\APP\toolBox\apps\PyCharm-P\ch-0\211.7142.13\plugins\python\helpers\pycharm_display
D:\APP\anaconda\python37.zip
D:\APP\anaconda\DLLs
D:\APP\anaconda\lib
D:\APP\anaconda
D:\APP\anaconda\lib\site-packages
D:\APP\anaconda\lib\site-packages\win32
D:\APP\anaconda\lib\site-packages\win32\lib
D:\APP\anaconda\lib\site-packages\Pythonwin
D:\APP\toolBox\apps\PyCharm-P\ch-0\211.7142.13\plugins\python\helpers\pycharm_matplotlib_backend
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 包
为了使 Python 应用更具可扩展性,你可以把多个模块组织成文件层次,称之为包
新建个叫test的包,pycharm中可以直接新建package,我们新建两个文件一个叫 one.py
一个叫 two.py
# one.py
def one():
print("1")
# two.py
def two():
print(2)
2
3
4
5
6
主程序我们这样写
from test import one,two
print(one.one())
print(two.two())
2
3
目录结构如下
# Python标准库
Python 的一个显著特点是具有庞大的模块标准库,这些模块可以执行很多有用的任务,并且和核心 Python 语言分开以避免臃肿。
# 使用counter计数
这个计数器可以返回列表中每个值出现的次数
from collections import Counter
a = ['a','b','c','a']
print(Counter(a))
----------
Counter({'a': 2, 'b': 1, 'c': 1})
2
3
4
5
6
# 使用orderedDict对字典进行排序
在前面几章的代码示例中可以看出,一个字典中键的顺序是不可预知的:你可以按照顺序 添加键 a、b 和 c,但函数 keys() 可能返回 c、a 和 b。下面是第 1 章用过的一个例子
>>> quotes = {
... 'Moe': 'A wise guy, huh?',
... 'Larry': 'Ow!',
... 'Curly': 'Nyuk nyuk!',
... }
>>> for stooge in quotes:
... print(stooge)
...
Larry
Curly
Moe
2
3
4
5
6
7
8
9
10
11
有序字典 OrderedDict() 记忆字典键添加的顺序,然后从一个迭代器按照相同的顺序返 回。 试着用元组(键,值)创建一个有序字典:
>>> from collections import OrderedDict
>>> quotes = OrderedDict([
... ('Moe', 'A wise guy, huh?'),
... ('Larry', 'Ow!'),
... ('Curly', 'Nyuk nyuk!'),
... ])
>>>
>>> for stooge in quotes:
... print(stooge)
...
Moe
Larry
Curly
2
3
4
5
6
7
8
9
10
11
12
13
# 双端队列: 栈+队列
deque 是一种双端队列,同时具有栈和队列的特征。它可以从序列的任何一端添加和删除项。具体细节查文档
from collections import deque
# 使用itertools迭代代码结构
itertools(https://docs.python.org/3/library/itertools.html)包含特殊用途的迭代器函数。在 for ... in 循环中调用迭代函数,每次会返回一项,并记住当前调用的状态。 即使 chain() 的参数只是单个迭代对象,它也会使用参数进行迭代
import itertools
for item in itertools.chain([1, 2], ['a', 'b']):
print(item)
1
2
a
b
2
3
4
5
6
7
# 使用 pprint()
友好输出
from pprint import pprint
from collections import OrderedDict
a = OrderedDict([
('Moe', 'A wise guy, huh?'),
('Larry', 'Ow!')
,('Curly', 'Nyuk nyuk!'),
])
print(a)
pprint(a)
-----------
OrderedDict([('Moe', 'A wise guy, huh?'), ('Larry', 'Ow!'), ('Curly', 'Nyuk nyuk!')])
OrderedDict([('Moe', 'A wise guy, huh?'),
('Larry', 'Ow!'),
('Curly', 'Nyuk nyuk!')])
2
3
4
5
6
7
8
9
10
11
12
13
14
15