Python标准库是一组模块,安装的Python都包含它。
使用模块collections中的OrderedDict类,创建字典并记录其中的键值对的添加顺序。
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " + language.title())
Reuslt:
Jen's favorite language is Python
Sarah's favorite language is C
Edward's favorite language is Ruby
课后练习:掷筛子得到随机数
from random import randint
class Die(object):
"""docstring for Die"""
def __init__(self, sides = 6):
self.sides = sides
def rool_die(self):
num = randint(1 , self.sides)
print("your dice num is " + str(num))
dice = Die()
dice.rool_die()
Result:
your dice num is 6