Python基本语法汇总

本文主要介绍Python语言的一些容易出错和比较特别的语法,以备不时之需。

通用序列

  • 序列求和及乘法
1
[1, 2] + [1, 2]
[1, 2, 1, 2]
1
[1, 2]*3
[1, 2, 1, 2, 1, 2]
1
'python'*3
'pythonpythonpython'
  • 成员资格检查
1
2
3
4
5
6
7
8
9
10
database = [
['albert', '1234'],
['dilbeter', '4567'],
['smith', '0789']
]
username = input('User name: ')
pin = input('PIN code: ')

if [username, pin] in database:
print('Acess granted')
User name: smith
PIN code: 0789
Acess granted

列表

  • 入栈和出栈
1
2
3
4
5
6
7
x = [1, 2]
# 入栈
x.append(3)
# 出栈
x.pop()
# 回到原来的堆栈
x
[1, 2]
  • 不带和带返回值的排序
1
2
3
4
5
6
7
8
9
x = [2, 8, 1, 7]
# 浅拷贝
y = x.copy()
# 不带返回值,修改x
x.sort()
# 带返回值
z = sorted(y)
print(x)
print(z)
[1, 2, 7, 8]
[1, 2, 7, 8]

字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 使用指定宽度打印价格列表
width = int(input('Please enter width: '))

price_width = 10
item_width = width - price_width

header_format = '%-*s%*s' # '-'表示左对齐,'*'表示参数从元组中读入
format = '%-*s%*.2f'

print ('='* width) # 表示复制width份'='

print (header_format %(item_width, 'Item', price_width, 'Price'))

print ('-' * width)

print (format %(item_width, 'Apple', price_width, 0.4))
print (format %(item_width, 'Pears', price_width, 12.5))

print ('=' *width)
Please enter width: 34
==================================
Item                         Price
----------------------------------
Apple                         0.40
Pears                        12.50
==================================

字典

  • 用字典创建简单数据库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 字典用人名作为键,每个人用另一个字典表示
people = {
'Alice': {
'phone': '2341',
'addr': 'Foo drive 233'
},
'Beth': {
'phone': '9102',
'addr': 'Bar street 42'
}
}

# 针对电话和地址使用描述性标签,在打印输出的时候使用
labels = {
'phone': 'phone number',
'addr': 'address'
}

name = input('Name: ')

# 查找电话还是地址?
request = input('Phone number (p) or address (a)?')

# 使用正确的键:
if request == 'p':
key = 'phone'
if request == 'a':
key = 'addr'

# 使用更宽松的取值方法get(),当不存在该键(第一个参数提供)时,返回默认值(第二个参数提供)
person = people.get(name, {})
label = labels.get(key, key)
result = person.get(key, 'not available')

print ("%s's %s is %s." % \
(name, label, result))
Name: Alice
Phone number (p) or address (a)?p
Alice's phone number is 2341.
  • 对比赋值、浅复制、深复制
1
2
3
4
5
6
7
8
9
# 赋值
x = {'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
y1 = x
y1['username'] = 'user'
y1['machine'].remove('bar')
print(x)
print(y1)
x = {}
print(y1)
{'machine': ['foo', 'baz'], 'username': 'user'}
{'machine': ['foo', 'baz'], 'username': 'user'}
{'machine': ['foo', 'baz'], 'username': 'user'}
1
2
3
4
x = {'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
y1 = x
x.clear()
print(y1)
{}

赋值语句表示关联,修改关联后的字典,也会修改原始字典。而且如果要清空原始字典,必须使用clear方法

1
2
3
4
5
6
# 浅复制
x = {'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
y2 = x.copy()
y2['username'] = 'user'
y2['machine'].remove('bar')
x
{'machine': ['foo', 'baz'], 'username': 'admin'}
  • 当在副本中替换值时,原字典不受影响
  • 当在副本中修改值(原地修改,而不是替换)时,原字典也会改变
1
2
3
4
5
6
7
# 深复制
from copy import deepcopy
x = {'username': 'admin', 'machine': ['foo', 'bar', 'baz']}# 深复制
y3 = deepcopy(x)
y3['username'] = 'user'
y3['machine'].remove('bar')
x
{'machine': ['foo', 'bar', 'baz'], 'username': 'admin'}

深复制可以将原字典的所有值复制给副本,副本的任何变化不影响原字典。

1
2
3
4
5
x = {}
y = x
x['key'] = 'value'
x={}
y
{'key': 'value'}

循环

  • 循环列表
1
2
3
numbers = [1, 2, 3]
for number in numbers:
print(number)
1
2
3
  • 循环字典
1
2
3
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key,'=',d[key])
z = 3
y = 2
x = 1
1
2
3
d = {'x': 1, 'y': 2, 'z': 3}
for key, value in d.items():
print(key,'=',value)
z = 3
y = 2
x = 1
  • 并行迭代工具
1
2
3
4
names = ['x', 'y']
ages = [31, 32]
for name,age in zip(names, ages):
print(name,'=',age)
x = 31
y = 32
  • 索引迭代
1
2
3
names = ['x', 'y']
for indx, name in enumerate(names):
print('name[%d]=%s'%(indx,name))
name[0]=x
name[1]=y
  • 列表推导式
1
[x*x for x in range(10) if x%3==0]
[0, 9, 36, 81]

函数

  • 收集参数:

在函数定义过程中, - 单星号表示以元组方式收集其余位置的参数 - 双星号表示以字典方式收集其余位置的参数

1
2
3
4
def print_params_1(title, *params):
print(title)
print(params)
print_params_1('Params:', 1, 2, 3)
Params:
(1, 2, 3)
1
2
3
4
5
def print_params_2(x,y, z=3, *pospar, **params):
print(x,y,z)
print(pospar)
print(params)
print_params_2(1, 2, 4, 5, 6, 7, foo=1, bar=2)
1 2 4
(5, 6, 7)
{'foo': 1, 'bar': 2}
  • 参数收集的逆过程

在函数调用过程中, - 单星号表示将元组中的值分配到函数各个位置上的参数上 - 双星号表示将字典中的值分配到函数各个键名的参数上

1
2
3
4
def add2(x, y):
return x+y
params = (1, 2)
add2(*params)
3
1
2
3
4
def hello_3(name, greeting):
print('%s, %s!'%(greeting, name))
params = {'name': 'Robin', 'greeting': 'Well met'}
hello_3(**params)
Well met, Robin!
  • 在定义和调用函数时都使用了星号,则相互抵消,不起作用。
1
2
3
4
5
6
7
8
9
def with_star(**kwds):
print(kwds['name'], kwds['age'])

def without_star(kwds):
print(kwds['name'], kwds['age'])

args = {'name': 'Gumby', 'age': 42}
with_star(**args)
without_star(args)
Gumby 42
Gumby 42
1
(5,)*2
(5, 5)

递归

  • 有效递归满足两个条件: > - 当函数直接返回值时,有基本实例(最小可能性问题); > - 递归实例,包括一个或者多个问题较小部分的递归调用。
1
2
3
4
5
6
7
# 阶乘
def factorial(n):
if n == 1:
return 1
else:
return n*factorial(n-1)
factorial(4)
24
1
2
3
4
5
6
7
# 幂
def pow_2(x, n):
if n == 0:
return 1
else:
return x*pow(x, n-1)
pow_2(10,2)
100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 二分查找
def search(sequence, number, lower=0, upper=None):
if upper is None:
upper = len(sequence)-1
if lower == upper:
assert number == sequence[upper]
return upper
else:
middle = (lower + upper) // 2
if number > sequence[middle]:
return search(sequence, number, middle+1, upper)
else:
return search(sequence, number, lower, middle)

seq = [34, 67, 8, 123, 4, 100, 95]
seq.sort()
search(seq, 34)
2

异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MuffledCalculator:
muffled = False
def calc(self, expr):
try:
return eval(expr)
except (ZeroDivisionError, TypeError) as e: #捕捉多种异常,并打印异常,继续执行程序
if self.muffled:
print(e)
else:
raise
else: # 没有坏事情发生时,执行以下代码
print('It went well as planned')
finally: # 对异常处理之后做一些清理工作,但是尽量不要用del,一般用来关闭文件之类。
pass
1
2
calculator = MuffledCalculator()
calculator.calc('10/0')
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-3-75f66264a28b> in <module>()
      1 calculator = MuffledCalculator()
----> 2 calculator.calc('10/0')


<ipython-input-2-f519639cf587> in calc(self, expr)
      3     def calc(self, expr):
      4         try:
----> 5             return eval(expr)
      6         except (ZeroDivisionError, TypeError) as e:  #捕捉多种异常,并打印异常,继续执行程序
      7             if self.muffled:


<string> in <module>()


ZeroDivisionError: division by zero
1
2
calculator.muffled = True
calculator.calc('10/0')
division by zero
1
calculator.calc('10/2')
5.0

参考资料

  1. Magnus Lie Hetland著,司维等人译,Python基础教程(第2版),2017