0 Python3.7简介
Python 是一门简单易学且功能强大的编程语言。它拥有高效的高级数据结构,并且能够用简单而又高效的方式进行面向对象编程。Python 优雅的语法和动态类型,再结合它的解释性,使其在大多数平台的许多领域成为编写脚本或开发应用程序的理想语言。
用 Python 编写的程序通常比同样的 C、C++ 或 Java 程序更短小,这是因为以下几个原因:
- 高级数据结构使你可以在一条语句中表达复杂的操作;
- 语句组使用缩进代替开始和结束大括号来组织;
- 变量或参数无需声明。
本文参考官方tutorial进行重点归纳总结,以供Python初学者快速入门。
1 Python解释器
Python 解释器通常被安装在目标机器的/usr/local/bin/python3
目录下,通过输入:
python3
命令启动它。
通常你可以在主窗口输入一个文件结束符(Unix系统是Ctrl-D,Windows系统是Ctrl-Z)让解释器以 0 状态码退出。如果那没有作用,你可以通过输入quit()
命令退出解释器。
- 可执行 Python 脚本
Unix 系统上,Python 脚本可直接执行,像 shell 脚本一样,只需要把下面内容加入到
#!/usr/bin/env python3
(假设 python 解释器在用户的 PATH 中)脚本的开头,并给予该文件的可执行模式:
chmod +x script.py
2 输入和输出
2.1 格式化输出
有2种输出方式:
- 表达式语句
- print()函数
① 逗号(,
)输出为空格分隔;
② %, %s, %d等
>>> print('string format: %d %s, %d' % (1,'and',3))
string format: 1 and, 3
③ str.format()
方法:str.format(*args, **kwargs)
输出字符串的{}
被替换。{}
内容为位置参数的数字下标或关键字参数名称。
{}
内可以使用:
,如:{0:.3f}
,{1:10d}
>>> print("What's your {1}?".format(1,23,45,6,'axs',one=1,two=2,three=3))
What's your 23? # positional index
>>> print("What's your {two}?".format(1,23,45,6,'axs',one=1,two=2,three=3))
What's your 2? # keyword name
>>> print('{0:.3f}'.format(123.4567))
123.457
2.2 输入
input()函数
:用户控制台输入。
birth = input('Birthday:') # get a str via user input
birth = int(birth) # change to int
if birth < 2000:
print('00前')
else:
print('00后')
2.3 文件读写
- 打开文件
函数open()
返回文件对象。open(file, mode='r')
f = open('/home/ywq/Downloads/1.txt', 'r', encoding='gb18030')
- 按行读取文件内容
for eachline in f: # eachline为str类型
print(eachline, end='')
- 写入内容
f = open(filename, 'w'):
f.write('something to write')
- 关闭文件
文件读写后要记得关闭:
f.close()
3 Python流程控制
3.1 if 语句
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
More
可能会有零到多个 elif 部分,else 是可选的。if … elif … elif …
序列用于替代其它语言中的 switch 或 case 语句。
3.2 for 语句
Python 的 for 语句依据任意 sequence(链表或字符串)中的子项,按它们在序列中的顺序来进行迭代。
常用序列见本文Sequence type部分。
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12
循环技巧:
- 字典中循环时,关键字和对应的值可以使用
items()
方法同时解读出来:
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
- 序列中循环时,索引位置和对应值可以使用
enumerate()
函数同时得到:
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
3.3 break, continue和循环中的else子句
break和continue语法和C中一样:
- break: 中断该层for或while循环。
- continue: 中断本次循环,继续下一次循环。
循环中的else子句:循环中可以有一个else语句,循环迭代完整个列表(对于 for )或执行条件为 false (对于 while )时执行,但循环被 break 中止的情况下不会执行。
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
3.4 pass语句
pass语句什么都不做。
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
3.5 定义函数
- 关键字
def
引入了一个函数 定义。 - 在其后必须跟有函数名和包括形式参数的圆括号。
- 函数体语句从下一行开始,必须是缩进的。
return
语句从函数中返回一个变量、返回多个变量时类型为tuple
,不带表达式的return
返回None
。
>>> def fib2(n): # return Fibonacci series up to n
... """Return a list containing the Fibonacci series up to n."""
... result = []
... a, b = 0, 1
... while a < n:
... result.append(a) # see below
... a, b = b, a+b
... return result
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
3.5.1 默认参数
- 为一个或多个参数指定默认值。这会创建一个可以使用比定义时允许的参数更少的参数调用的函数,
- 函数引用的实际参数在函数调用时引入局部符号表,因此,实参总是引用传递。
3.5.2 关键字参数
函数可以通过 关键字参数 的形式来调用,形如 keyword = value
.
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
接受一个必选参数 (voltage)
以及三个可选参数 (state, action, 和 type)
。可以用以下的任一方法调用:
parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
注意:关键字参数必须跟随在位置参数的后面
3.5.3 可变参数列表
可变个数的参数。这些参数被包装进一个list或tuple,在这些可变个数的参数之前,可以有零到多个普通的参数:
def write_multiple_items(file, *args, sep="/"): # Positional ... Arbitrary ... Keyword
file.write(sep.join(args))
注意:*args, **kwargs
区别:
*args
接收一个list或元组(*变量
)——多个参数值。**kwargs
接收一个字典(**变量
)——多个关键字参数。
def cal(*args, **kwargs):
for x in args:
print(x)
for k in kwargs: # for k, v in kwargs.item():
print('%s = %d' % (k, kwargs[k])) # print('%s = %d' % (k, v))
l = [1,2,3,4]
d = {'x':1,'xx':2}
cal(*l, **d) # print: 1
# 2
# 3
# 4
# x = 1
# xx = 2
3.5.4 Lambda表达式
- 创建短小的匿名函数。
- 出于语法限制,它们只能有一个单独的表达式。
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
4 数据结构
Python数据结构详细内容可参阅官方文档.
4.1 Basic data types
—— integers, floats, booleans, and strings
- Numbers: Integers, floats, complex
operation | result |
---|---|
math.trunc(x) | x truncated to Integral |
round(x[, n]) | x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0. |
math.floor(x) | the greatest Integral <= x |
math.ceil(x) | the least Integral >= x |
>>> x = 3
>>> type(x)
<class 'int'>
>>> print(x + 1) # Addition
4
>>> print(x * 2) # Multiplication
6
>>> print(x ** 2) # Exponentiation
9
>>> print(x / 2) # Division
1.5
>>> print(x // 2) #
1
>>> a = math.trunc(3.1415)
>>> a
3
>>> a = round(3.1415,3)
>>> a
3.142
- Booleans: and, or, not
>>> a, b, c = 1, 2, 3
>>> if a == 1 and b < c:
... print('a equals 1, b is smaller than c')
...
a equals 1, b is smaller than c
- Strings: 字符串内容见string.
4.2 Sequence Types
基本顺序类型有3个——list, tuple, range
- sequence types通用操作
a = [1, 2, 3]
b = [4, 5, 6]
a + b # value: [1, 2, 3, 4, 5, 6]
a.index(2) # value: 1
>>> a.index(3, 0, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 3 is not in list
注意:序列中item不是copy,而是多次reference.注意以下区别:
lists = [[]] * 3 # lists = [[], [], []]
lists[0].append(3) # lists = [[3], [3], [3]]
lists = [[] for i in range(3)] # lists = [[], [], []]
lists[0].append(3) # lists = [[3], [], []]
lists[1].append(5) # lists = [[3], [5], []]
lists[0].append(7) # lists = [[3, 7], [5], []]
- mutable sequences types操作
——list, dict, set
4.2.1 list
classlist
(
[
iterable
]
)
¶
a = [1, 2, 3, 4]
b = [[1, 2, 3], [4]]
c = [i in range(5)] # c = [0, 1, 2, 3, 4]
d = list(range(5)) # d = [0, 1, 2, 3, 4]
- Slicing: access sublists.
nums = list(range(5)) # range is a built-in function that creates a list of integers
print(nums) # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2]) # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:]) # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]"
print(nums[:-1]) # Slice indices can be negative; prints "[0, 1, 2, 3]"
nums[2:4] = [8, 9] # Assign a new sublist to a slice
print(nums) # Prints "[0, 1, 8, 9, 4]"
- Loops:
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal)
# Prints "cat", "dog", "monkey", each on its own line.
- List comprehensions:
# list comprehension
nums = [0, 1, 2, 3]
squares = [x ** 2 for x in nums] # squares = [0, 1, 4, 9]
L = [x + y for x in 'ABC' for y in 'XYZ'] # L = ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
除了sequence type通用操作和mutable sequence操作,list还有:
sort
(
*,
key=None,
reverse=False
)
¶
4.2.2 tuple
classtuple
(
[
iterable
]
)
¶
注意:tuple和list很相似,除了:
- tuple 是immutable sequence, 只能实现sequence type通用操作
- tuple 可以作为
dict的keys
和Sets的元素
。
a = (1, 2, 3)
b = 4, a # b = (4, (1, 2, 3))
c = tuple(i for i in range(3)) # c = (0, 1, 2)
t =(1,) # tupe with only one element
4.2.3 range
classrange
(
stop
)
¶
class
range
(
start,
stop
[,
step
]
)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
range是immutable sequence type,只能实现sequence type通用操作。
4.3 Text Sequence Type — str
class str
(object=’’)¶
str
(
object=b'',
encoding='utf-8',
errors='strict'
)
str是immutable sequence type,只能实现sequence type通用操作。
String文本有许多方式书写:
- 单引号:
‘allows embedded “double” quotes’
- 双引号:
“allows embedded ‘single’ quotes”
- 三引号:
’’‘Three single quotes’’’
,“”“Three double quotes”""
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[-1] # last character
'n'
4.4 Mapping Types — dict
class dict
(**kwarg)¶
class dict
(mapping, **kwarg)
class dict
(iterable, **kwarg)
pairs = (key, value)
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) # pairs = zip(d.values(), d.keys())
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
- Dictionary comprehensions:
key = ['one', 'two', 'three','four']
value = [1,2,3,4]
d = {key[i]: value[i] for i in range(len(key)) if i % 2 ==0}
print(d) # print: {'three': 3, 'one': 1}
print(d['one']) # print: 1
避免key不存在的错误:
- 通过
in
判断key是否存在:
d = {'a':1, 'b':2, 'c':3}
print('a'in d) # print: True
dict.get()方法
:key不存在,可以返回None
,或者自己指定的value
print(d.get('b')) # print: 2
print(d.get('d', -10)) # print: -10
4.5 Set Types — set
class set
([iterable])¶
animals = {'cat', 'dog'}
animals.add('fish')
animals.remove('dog')
a = set([0,1,2])
b = set(range(3))
- Loops:
enumerate
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
# Prints "#1: fish", "#2: dog", "#3: cat"
- Set comprehensions:
from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums) # Prints "{0, 1, 2, 3, 4, 5}"
5 高级特性
可直接作用于for
循环的数据类型都是可迭代对象:Iterable
,主要有两种:
iterator迭代器
,如集合数据类型:list
、tuple
、str
、dict
、set
generator生成器
- 凡是可以
for
循环的,都是Iterable
- 凡是可以
next()
的,都是Iterator
list
、tuple
、str
、dict
是Iterable
,但不是Iterator
,可以使用iter()
函数将其变为Iterator
from collections import Iterable
print(isinstance([], Iterable)) # print: True
print(isinstance((), Iterable)) # print: True
from collections import Iterator
print(isinstance([], Iterator)) # print: False
print(isinstance(iter(()), Iterator)) # print: True
print(isinstance({}, Iterator)) # print: False
print(isinstance('xxx'.__iter__(), Iterator)) # print: True
5.1 迭代器 — Iterator
迭代器是包含__iter__
和__next__
方法的类。
创建一个iterator
,必须实现一个有__iter__()
和__next__()
方法的类,类要能够跟踪内部状态并且在没有元素返回的时候引发StopIteration
异常.
class Fibs:
def __init__(self, threshold=20):
self.a = 0
self.b = 1
self.maxnum = threshold
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > self.threshold:
raise StopItearation
else:
return self.a
使用该迭代器:
fib = Fibs()
for each in fib:
print each # 依次打印 1, 1, 2, 3, 5, 8, 13
5.2 生成器 — generator
生成器是特殊类型的迭代器。
Python generator可以方便地创建iterator,自动实现__iter__
和__next__
方法。
——边循环边计算、按需生成。
- 方法一:列表生成器的
[]
改为()
产生generator
g = (x ** 2 for x in range(3)) # g: <generator object <genexpr> at 0x7fc5cf37a728>
print(next(g)) # print: 0
print(next(g)) # print: 1
print(next(g)) # print: 4
print(next(g)) # Exception: StopIteration
使用for
循环可以自动捕获StopIteration
异常:
for x in g:
print(x)
- 方法二:generator函数
- generator函数包含一个以上的
yield
声明- generator函数被调用的时候,会返回一个iterator对象,但是函数并不会立即开始执行
__iter__()
和__next__()
方法被自动实现,所以可以使用next()
函数对返回的此iterator对象进行迭代。- 函数执行过程:每调用一次
next()
,生成器函数就运行到一个yield处,并保存状态且返回yield后的数据,下次调用next
,生成器函数从上次yield语句后开始运行,直到没有yield语句后,函数执行到末尾,再调用next
就会触发StopIteration
异常。
def my_gen():
n = 10
print('1st')
yield n
n += 1
print('2nd')
yield n
n+=1
print('3rd')
yield n
g = my_gen()
print(g.__next__()) # print: 1st
# 10
g.__next__() # print: 2nd
next(g) # print: 3rd
6 模块 Module
Python中一个
.py
文件就称之为模块(Module).
如:abc.py
文件就是一个名字叫abc
的模块。
如果模块名字冲突,可以通过包来组织模块,避免冲突。
如下文件目录:
mycompany
├─ __init__.py
├─ abc.py
└─ xyz.py
模块名变为:mycompany.abc
和mycompany.xyz
注意:每个package包
目录下都有一个__init__.py
的文件,以表明这是一个Python包。
__init__.py
可以是空文件,也可以有Python代码。- 包含有多个模块。
- 从包内导入模块:
import mycompany.abc as abc
6.1 使用模块
Python内置了很多有用的模块,可以立即使用(import ... as ...
),自己编写的模块也能立即使用。
file: one.py
:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ywq'
def func():
print('func() in one.py')
print('top-level in one.py')
if __name__ == '__main__':
print('one.py is runing directly')
else:
print('one.py is imported into another module')
file two.py
:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ywq'
import one # start executing one.py
print('top-level in two.py')
one.func()
if __name__ == '__main__':
print('two.py is runing directly')
else:
print('two.py is imported into another module')
运行python3 one.py
,输出:
top-level in one.py
one.py is runing directly
运行python3 two.py
,输出:
top-level in one.py
one.py is imported into another module
top-level in two.py
func() in one.py
two.py is runing directly
说明:if __name__ == '__main':
只有在直接运行模块时为True
,被其他模块导入时为False
.
6.2 安装第三方模块
一般来说,第三方库都会在Python官方网站注册,要安装一个第三方库,必须先知道该库的名称,可以在官网或者pypi上搜索,再使用安装命令:
python3 -m pip install xxx
# 或者
pip3 install xxx
- 模块搜索路径
模块搜索路径在sys
模块的path
变量中。
使用import
导入模块时,系统会从搜索路径中查找模块。
>>> import sys
>>> sys.path
['', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/ywq/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages']
注意:该结果中'/home/ywq/.local/lib/python3.5/site-packages'
路径为pip3
方式安装第三方库的存储位置。
添加搜索路径的方法:
方法一:直接修改sys.path
值,添加要搜索的目录:>>> import sys >>> sys.path.append('/Users/michael/my_py_scripts')
在运行时修改,运行结束后失效。
方法二:设置环境变量
PYTHONPATH
:
在/etc/profile.d
下建立python.sh
文件,并在文件最后加入代码,如:export PYTHONPATH=/home/ywq/Documents/:$PYTHONPATH
终端输入
$ source /etc/profile
使配置生效.
注意:python3 -m
中-m
表示以模块方式执行python文件(命令),主要是把输入命令的目录(也就是当前路径),放到了sys.path属性中.