In [ ]:
# 异常
try:
    file = open('test.txt', 'rb')
except IOError as e:
    print("An IOError occurrend. {}".format(e))
    
# 多异常
try:
    file = open('test.txt', 'rb')
except EOFError as e:
    print("An EOF error occured.")
except IOError as e:
    print("An error occourred.")
    #raise e
    
# 捕捉所有异常
try:
    file = open('test.txt', 'rb')
except Exception as e:
    raise e

In [ ]:
# try/else从句
try:
    print('I am sure no exception is going to occur!')
except Exception:
    print('exception')
else:
    # 这里的代码只会在try语句里没有触发异常时运行
    # 但是这里的异常 *不会* 被捕捉
    print('This  wrold only run if no exception occurs, And an error would NOT be caught.')
finally:
    print('This would be printed in every case.')

In [ ]:
a = [(1,2), (4,1), (9,10),(13,-3)]
a.sort(key=lambda x: x[1])
print(a)

# 列表并行排序
list1 = [1,3,4,5]
list2 = [9,2,4,5,1,7,5,4]
data = zip(list1, list2)
print(data)
list1, list2 = map(lambda t: list(t), zip(*data))
print(list1)
print(list2)

In [ ]:
# 漂亮的打印
from pprint import pprint
my_dict = {'name':'Yasoob', 'age':'undefined', 'personality':111}
pprint(my_dict)

In [ ]:
import itertools as it
a_list = [[1,2],[3,4],[5,6]]
print(list(it.chain.from_iterable(a_list)))

In [ ]:
class A(object):
    def __init__(self, a, b, c, d, e, f):
        self.__dict__.update({k:v for k, v in locals().items})
        
obj_a = A(1,2,3,4,4,5)
print(obj_a)

In [ ]:
furits = ['apple','banana','mango']
for furit in furits:
    print(furit.capitalize())
    
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')

In [ ]:
import io
with open('otherfile.txt', 'rb') as f:
    jpgdata = f.read()
    
if jpgdata.startswith(b'\xff\xd8'):
    text = 'This is jpeg file (%d bytes long)\n'
else:
    text = 'This is random file (%d bytes long)\n'
    
with io.open('summary.txt', 'w', encoding='utf-8') as out_f:
    out_f.write(text % len(jpgdata))

In [ ]:
# 生成器的创建
def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a+b

for i in fib():
    print(i)

In [ ]:
# 协程
def grep(pattern):
    print("searching for", pattern)
    while True:
        line = (yield)
        if pattern in line:
            print(line)
            
search = grep('coroutine')
next(search) # 通过next方法启动协程
search.send('I love you.')
search.send("Don't you love me")
search.send("I love coroutine instead!")

search.close() # 关闭协程

In [ ]:
# 函数缓存
from functools import lru_cache
@lru_cache(maxsize=32)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

print([fib(n) for n in range(10)])
fib.cache_clear() # 清空缓存

In [ ]:
from functools import wraps

# python2.x 缓存
def memoize(func):
    memo = {}
    @wraps(func)
    def wrapper(*args):
        if args in memo:
            return memo[args]
        else:
            rv = func(*args)
            memo[args] = rv
            return rv
    return wrapper


@memoize
def fib(n):
    if n < 2: return n
    return fib(n-1) + fib(n-2)

print([fib(n) for n in range(10)])

In [ ]:
# 上下文管理器的类
class File(object):
    def __init__(self, file_name, method):
        print('__init__')
        self.file_obj = open(file_name, method)
    def __enter__(self):
        print('__enter__')
        return self.file_obj
    def __exit__(self, type, value, traceback):
        print('__exit__')
        print("Exception has been handled")
        self.file_obj.close()
        return True # 返回true时候没有异常被with语句抛出

with File('demo.txt', 'w') as opened_file:
#     opened_file.write('Hola!')
    opened_file.undefined_function('Hola!')

In [48]:
from contextlib import contextmanager
@contextmanager
def open_file(name):
    f = open(name, 'w')
    yield f
    f.close()
    
with open_file('demo.txt') as f:
    f.write("......hula!")

In [ ]: