第二题:-1
第三题:list
第四题:key in dict
第五题:false
第六题:return
第七题:开源
第八题:
第九题:dict.get(key)
第十题:(1)无参数,无返回值;(2)无参数,有返回值的函数;(3)有参数,无返回值的函数;(4)有参数,有返回值的函数
#!/usr/bin/env python#coding=utf-8
import re
from datetime import datetime as dt, timedelta
import platform
if platform.python_version()[:1] == '2': #判断python版本是2还是3
import sys
reload(sys)
sys.setdefaultencoding('utf8')
class Idcard(object):
'''
>>> m = Idcard('225122198611134730')
>>> print(m.sex)
男
>>> m.birth
'1986-11-13'
>>> m.age
30
'''
def __init__(self,idcard):
self.idcard = idcard
if len(idcard) == 15:
sex, birth = idcard[-1:], '19' + idcard[6:12]
elif len(idcard) == 18:
sex, birth = idcard[-2:-1], idcard[6:14]
else:
raise Exception('len(idcard) is {} (15/18)'.format(len(idcard)))
self._sex = int(sex) % 2
self._birth = birth
@property
def sex(self):
return u'男' if self._sex % 2 else u'女'
@property
def age(self):
now, bir = dt.now(), dt.strptime(self._birth, '%Y%m%d')
beforebirth = (now - dt(now.year, bir.month, bir.day)).days < 0
return dt.now().year - int(self._birth[:4]) - beforebirth
@property
def birth(self):
return dt.strptime(self._birth, '%Y%m%d').strftime('%Y-%m-%d')
def alignment(str1, space, align = 'left'):
length = len(str1.encode('gb2312'))
space = space - length if space >=length else 0
if align == 'left':
str1 = str1 + ' ' * space
elif align == 'right':
str1 = ' '* space +str1
elif align == 'center':
str1 = ' ' * (space //2) +str1 + ' '* (space - space // 2)
return str1
def main():
fname = 'customer.txt'
'''
with open(fname, 'w') as f:
f.write("""
郑文杰 225122198611134730
文萍 225122198912094740
郑妈妈 225122590303476
郑爸爸 225122560506471
""")
'''
newf = 'ourcustomers.txt'
with open(fname) as f:
s = f.readlines()
L, newL = [re.split(r'\s+', i.strip()) for i in s], []
for i in L:
if len(i) == 2:
g = Idcard(i[1])
newL.append('{}{}{}'.format(
alignment(i[0], 10), alignment(g.sex, 8), g.age))
with open(newf, 'w') as f:
f.write('\n'.join(newL))
print('\n'.join(newL[:100]))
print('Customer data has been write into {}'.format(newf))
if __name__ == '__main__':
import doctest
doctest.testmod()
main()
CSDN上找。进入公众号主页,点击右上角搜索按钮,输入作业题目关键字,获取答案。CSDN是功能齐全,大部分题目都可以搜到。
Python提供了高效的高级数据结构,还能简单有效地面向对象编程。Python语法和动态类型,以及解释型语言的本质,使它成为多数平台上写脚本和快速开发应用的编程语言,随着版本的不断更新和语言新功能的添加,逐渐被用于独立的、大型项目的开发。