- 5.1 print and import
- 5.1.1 打印多个参数
- 5.1.2 导入时重命名
- 5.2 赋值魔法
- 5.2.1 序列解包(unpack; v. 打开,取出)
- 5.2.2 链式赋值
- 5.2.3 增强赋值
- 5.2.4 代码块:缩进的乐趣
- 5.4 条件和 if 语句
- 5.4.1 布尔值
- 5.4.2 if 语句
- 5.4.3 else 子句
- 5.4.4 elif 子句
- 5.4.5 代码块嵌套
- 5.4.6 更复杂的条件
- part 1 比较运算符
- part 2 布尔运算符
- 5.4.7 断言
- 5.5 循环
- 5.5.1 while 循环
- 5.5.2 for 循环
- 5.5.3 迭代字典
- 5.5.4 一些迭代工具
- 5.5.4.1 并行迭代
- 5.5.4.2 迭代时获取索引
- 5.5.5 跳出循环
- 5.5.5.1 break
- 5.5.5.2 continue
- 5.5.5.3 while True/break 成例
- 5.5.6 else
- 5.6 列表推导
- 5.7 pass、del和exec
- 5.7.1 pass
- 5.7.2 del
- 5.7.3 exec and eval
- 5.7.3.1 exec
- 5.7.3.2 eval
5.1 print and import
5.1.1 打印多个参数
- print 函数可打印 string and number ;
>>> greeting = 'Hello,'
>>> salutation = 'Mr'
>>> name = 'Gumby'
>>> print(greeting, salutation, name)
Hello, Mr Gumby
>>> greeting = 'Hello'
>>> print(greeting + ',', salutation, name)
>>> print('I', 'wish', 'to', 'register', 'a', 'complaint', sep = '_')
I_wish_to_register_a_complaint
>>> print('Hello,', end = '')
>>> print('world!')
Hello,world!
5.1.2 导入时重命名
- import modules and functions;
>>> import somemodule
>>> from somemodule import somefunction
>>> from somemodule import function1, function2, function3
>>> from somemodule import *
- 若导入的两个 module 中包含相同函数名;
>>> module1.open(...)
>>> module2.open(...)
>>> from module1 import open as open1
>>> from module2 import open as open2
5.2 赋值魔法
5.2.1 序列解包(unpack; v. 打开,取出)
- 序列解包/可迭代对象解包:将序列 or 可迭代对象解包,所得值并行赋值给其他变量;
- 序列解包时,等号左右元素数量须保持相等,否则引发异常;
>>> x, y, z = 1, 2, 3
>>> x, y, z = (1, 2, 3)
>>> x, y = y, x
>>> a, b, *rest = [1, 2, 3, 4]
>>> test
>>> [3, 4]
>>> name = "Albus Percival Wulfric Brian Dumbledore"
>>> first, *middle, last = name.split()
>>> middle
['Percival', 'Wulfric', 'Brian']
5.2.2 链式赋值
>>> x = y = somefunction()
5.2.3 增强赋值
- 增强赋值可用于 number and string ;
>>> x += 1
>>> fnord = 'bar'
>>> fnord *= 2
5.2.4 代码块:缩进的乐趣
5.4 条件和 if 语句
5.4.1 布尔值
>>> True = 1
True
>>> True + False + 42
43
>>> () != False
True
>>> name = input("Please input your name: ")
>>> num1 = name.startswith('Andrew')
>>> num2 = name.endswith('Pan')
>>> print(num1)
>>> print(num2)
5.4.2 if 语句
5.4.3 else 子句
>>> name = input('What is your name? ')
>>> status = 'friend' if name.endswith('Gumby') else 'stranger'
>>> print(status)
5.4.4 elif 子句
5.4.5 代码块嵌套
5.4.6 更复杂的条件
part 1 比较运算符
表达式 |
功能 |
x is y |
x、y是同一个对象 |
x is not y |
x、y是不同的对象 |
x in y |
x是容器(e.g. 序列)y的成员 |
x not in y |
x不是容器(e.g. 序列)y的成员 |
>>> num = int(input('Enter a number between 1 and 10: '))
>>> if 1 <= num <= 10:
... print('Great!')
>>> x = y = [1,2,3]
>>> z = [1,2,3]
>>> x is y
True
>>> x is z
False
>>> name = input('What is your name? ')
>>> if 's' in name:
... print('Your name contains the letter "s".')
... else:
... print('Your name does not contain the letter "s".')
>>> ord('A')
65
>>> ord('a')
97
>>> [1,2] < [2,1]
True
>>> [2, [1,4]] < [2,[1,5]]
True
part 2 布尔运算符
- 布尔运算符:and、or、not;
- 短路逻辑:亦称 延迟求值 ;
e.g. x and y,
若 x 为假,则表达式不再继续判断,而是立即返回 x ;
若 x 为真,则返回 y ;
>>> name = input('Please enter your name: ') or ''
... Please enter your name:
>>> name
''
5.4.7 断言
# assert 布尔表达式
# assert 布尔表达式, '描述性 string'
# 上述两种格式均可;
>>> age = -1
AssertionError Traceback (most recent call last)
in ()
1 age = -1
----> 2 assert 0 < age < 100, 'The age must be realistic'
AssertionError: The age must be realistic
5.5 循环
5.5.1 while 循环
>>> name = ''
>>> while not name:
... name = input('Please enter your name: ')
>>> print('Hello, {}!'.format(name))
>>> name = ''
>>> while name.isspace() or not name:
... name = input('Please enter your name: ')
>>> print('Hello, {}!'.format(name))
5.5.2 for 循环
- 可迭代对象:可使用 for 循环遍历的对象;
- 函数 range():
range(0,10):返回整数列表[0,1,2,3,4,5,6,7,8,9];
range(10):默认起始值为0,返回整数列表[0,1,2,3,4,5,6,7,8,9];
>>> for number in range(1,101):
... print(number)
5.5.3 迭代字典
>>> d = {'x':1, 'y':2, 'z':3}
>>> for key in d:
... print(key, 'correspond to', d[key])
>>> d = {'x':1, 'y':2, 'z':3}
>>> for key in d.keys():
... print(key,'correspond to',d[key])
>>> d = {'x':1, 'y':2, 'z':3}
>>> for key,value in d.items():
... print(key,'correspond to',value)
5.5.4 一些迭代工具
5.5.4.1 并行迭代
>>> names = ['anne', 'beth', 'george', 'damon']
>>> ages = [12, 45, 32, 102]
>>> for i in range(len(names)):
... print(names[i], 'is', ages[i], 'years old')
>>> for name,age in zip(names, ages):
... print(name, 'is', age, 'years old')
>>> list(zip(range(5), range(10000)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
5.5.4.2 迭代时获取索引
>>> for index,string in enumerate(strings):
... if 'xxx' in string:
... strings[index] = '[censored]'
5.5.5 跳出循环
5.5.5.1 break
5.5.5.2 continue
5.5.5.3 while True/break 成例
5.5.6 else
5.6 列表推导
>>> [x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>> squares = {i:"{} squared is {}".format(i, i**2) for i in range(10)}
>>> squares[8]
'8 squared is 64'
5.7 pass、del和exec
5.7.1 pass
5.7.2 del
>>> x = 1
>>> y = x
>>> x
1
>>> y
1
>>> x = None
>>> x
>>> y
1
>>> y = None
>>> x
>>> y
>>> x = 1
>>> y = x
>>> del x
>>> y
1
>>> x
Traceback (most recent call last):
File "", line 1, in
NameError: name 'x' is not defined
5.7.3 exec and eval
5.7.3.1 exec
>>> from math import sqrt
>>> scope = {}
>>> exec('sqrt = 1', scope)
>>> sqrt(4)
2.0
>>> scope['sqrt']
1
>>> scope.keys()
dict_keys(['__builtins__', 'sqrt'])
5.7.3.2 eval
# eval 计算用 string 表示的 Python 表达式的值(evaluate);
>>> eval(input("Enter an arithmetic expression: "))
Enter an arithmetic expression: 6 + 18 * 2
42