Python 语言及其应用 Chapter_4_Exercise

来源:互联网 发布:2017网络灰色赚钱项目 编辑:程序博客网 时间:2024/04/30 05:03

课后小练习:

1:   使用字典推导创建字典squares。把0~9 内的整数作为键,每个键的平方作为对应的
 值。
>>> squares = {key: key*key for key in range(10)}
 >>> squares
 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}



2:   使用集合推导创建集合odd,包含0~9 内(range(10))的奇数。
>>> odd = {number for number in range(10) if number % 2 == 1}           #这一段我自己写成   odd={n for n in range(10) if n%2!=0}
 >>> odd
 {1, 3, 9, 5, 7}



3:   使用生成器推导返回字符串'Got ' 和0~9 内的一个整数,使用for 循环进行迭代。
>> for thing in ('Got %s' % number for number in range(10)):                       #两层嵌套,注意一下,原来没看到过
... print(thing)
 ...
 Got 0
 Got 1
 Got 2
 Got 3
 Got 4
 Got 5
 Got 6
 Got 7
 Got 8
 Got 9



4:   定义一个生成器函数get_odds():返回0~9 内的奇数。使用for 循环查找并输出返回的
 第三个值。
>>> def get_odds():
 ... for number in range(1, 10, 2):
 ... yield number
 ...
 >>> for count, number in enumerate(get_odds(), 1):    #这里指定序列索引从1开始
 ... if count == 3:
 ... print("The third odd number is", number)
 ... break
 ...
 The third odd number is 5



5: 定义一个装饰器test:当一个函数被调用时输出'start',当函数结束时输出'end'。
>>> def test(func):
... def new_func(*args, **kwargs):
... print('start')
... result = func(*args, **kwargs)
... print('end')
... return result
... return new_func
...
>>>
>>> @test
... def greeting():
... print("Greetings, Earthling")
...
>>> greeting()
start

Greetings, Earthling
end


6 :  定义一个异常OopsException:编写代码捕捉该异常,并输出'Caught an oops'。
>>> class OopsException(Exception):         #自定义一个错误子类,继承于Exception
... pass
...
>>> raise OopsException()                          #引发一个错误,我的理解是看看这个错误里面有些什么
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.OopsException
>>>
>>> try:
... raise OopsException
... except OopsException:
... print('Caught an oops')
...
Caught an oops



7: 使用函数zip() 创建字典movies: 匹配两个列表titles = ['Creature of Habit',
'Crewel Fate'] 和plots = ['A nun turns into a monster', 'A haunted yarn shop']。
>>> titles = ['Creature of Habit', 'Crewel Fate']
>>> plots = ['A nun turns into a monster', 'A haunted yarn shop']
>>> movies = dict(zip(titles, plots))
>>> movies
{'Crewel Fate': 'A haunted yarn shop', 'Creature of Habit': 'A nun turns
into a monster'}






0 0
原创粉丝点击