>>> for i, value in enumerate(['A', 'B', 'C']): ... print(i, value) ... 0 A 1 B 2 C #对比: for i in enumerate(['A', 'B', 'C']): print(i)
上面的for循环里,同时引用了两个变量,在Python里是很常见的,比如下面的代码:
1 2 3 4 5 6
>>> for x, y in [(1, 1), (2, 4), (3, 9)]: ... print(x, y) ... 1 1 2 4 3 9
练习
请使用迭代查找一个list中最小和最大值,并返回一个tuple:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
deffindMinAndMax(L): max = None min = None for i in L: ifmax == Noneormax < i : max = i ifmin == Noneormin > i : min = i # print(max) # print(min) return (min, max)
>>> L = ['Hello', 'World', 18, 'Apple', None] >>> [s.lower() for s in L] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <listcomp> AttributeError: 'int' object has no attribute 'lower'
使用内建的isinstance函数可以判断一个变量是不是字符串:
1 2 3 4 5 6
>>> x = 'abc' >>> y = 123 >>> isinstance(x, str) True >>> isinstance(y, str) False
请修改列表生成式,通过添加if语句保证列表生成式能正确地执行:
1 2 3 4
# -*- coding: utf-8 -*- L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [ s.lower() for s in L1 if isinstance(s, str)] print(L2)
def product(x, *arge): for i in arge: x = x * i return x def product_new(*num): if num is None or len(num) < 1 : raise TypeError("args not null!") else : sum = 1 for i in num : sum = sum * i return sum # 测试 if __name__ == '__main__': print('product(5) =', product(5)) print('product(5, 6) =', product(5, 6)) print('product(5, 6, 7) =', product(5, 6, 7)) print('product(5, 6, 7, 9) =', product(5, 6, 7, 9)) if product(5) != 5: print('测试失败!') elif product(5, 6) != 30: print('测试失败!') elif product(5, 6, 7) != 210: print('测试失败!') elif product(5, 6, 7, 9) != 1890: print('测试失败!') else: try: product() print('测试失败!') except TypeError: print('测试成功!')
>>> my_abs(1, 2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: my_abs() takes 1 positional argument but 2 were given
但是如果参数类型不对,Python解释器就无法帮我们检查。试试my_abs和内置函数abs的差别:
1 2 3 4 5 6 7 8 9 10
>>> my_abs('A') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in my_abs TypeError: unorderable types: str() >= int() >>> abs('A') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: bad operand type for abs(): 'str'
>>> fact(1000) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in fact ... File "<stdin>", line 4, in fact RuntimeError: maximum recursion depth exceeded in comparison
>>> classmates[0] 'Michael' >>> classmates[1] 'Bob' >>> classmates[2] 'Tracy' >>> classmates[3] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
>>> classmates[-2] 'Bob' >>> classmates[-3] 'Michael' >>> classmates[-4] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range