文章目录
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 Python流程控制
2.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 语句。
2.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
2.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
2.4 pass语句
pass语句什么都不做。
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
2.5 定义函数
- 关键字
def
引入了一个函数 定义。 - 在其后必须跟有函数名和包括形式参数的圆括号。
- 函数体语句从下一行开始,必须是缩进的。
return
语句从函数中返回一个值,不带表达式的 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]
2.5.1 默认参数
- 为一个或多个参数指定默认值。这会创建一个可以使用比定义时允许的参数更少的参数调用的函数,
- 函数引用的实际参数在函数调用时引入局部符号表,因此,实参总是引用传递。
2.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
注意:关键字参数必须跟随在位置参数的后面
2.5.3 可变参数列表
可变个数的参数。这些参数被包装进一个元组,在这些可变个数的参数之前,可以有零到多个普通的参数:
def write_multiple_items(file, *args, sep="/"): # Positional ... Arbitrary ... Keyword
file.write(sep.join(args))
2.5.4 Lambda表达式
- 创建短小的匿名函数。
- 出于语法限制,它们只能有一个单独的表达式。
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
3 数据结构
Python数据结构详细内容可参阅官方文档.
3.1 Boolean Operations
—— 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
3.2 Numeric Types
—— int, float, complex
- int, float通用操作:
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 |
>>> a = math.trunc(3.1415)
>>> a
3
>>> a = round(3.1415,3)
>>> a
3.142
3.3 Sequence Types
基本顺序类型有3个——list, tuple, range
- sequence types通用操作
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>> a.index(2)
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[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
- mutable sequences types操作
——list, dict,
3.3.1 list
list
(
[
iterable
]
)
¶
>>> a = [1, 2, 3, 4]
>>> b = [[1, 2, 3], [4]]
>>> c = [i in range(5)]
>>> d = list(range(5))
>>> a
[1, 2, 3, 4]
>>> b
[[1, 2, 3], [4]]
>>> c
[0, 1, 2, 3, 4]
>>> d
[0, 1, 2, 3, 4]
除了sequence type通用操作和mutable sequence操作,list还有:
sort
(
*,
key=None,
reverse=False
)
¶
3.3.2 tuple
tuple
(
[
iterable
]
)
¶
>>> a = (1, 2, 3)
>>> b = 4, a
>>> c = tuple(i for i in range(3))
>>> a
(1, 2, 3)
>>> b
(4, (1, 2, 3))
>>> c
(0, 1, 2)
tuple是immutable sequence type,只能实现sequence type通用操作。
3.3.3 range
range
(
stop
)
¶
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通用操作。
3.3.4 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'