本文共 2581 字,大约阅读时间需要 8 分钟。
python 练习代码
练习1: 输入:年、月(1-12)、日(1-31) 打印出相应的月份、名称months=['Janary','February','March','April','May','June','July','August','September','October','November','December']endings=['st','nd','rd']+7*['th']+['st','nd','rd']+7*['th']+['st','nd','rd']+7*['th']+['st']year=raw_input('Year: ')month=raw_input('Month(1-12): ')day=raw_input('Day(1-31): ')month_number=int(month)day_number=int(day)month_date=months[month_number-1]day_date=day+endings[day_number-1]print month_date+' '+day_date+' ‘+year
练习2:
输入人名,查询电话号码或居住地址people={ 'Alice':{ 'phone':'2341','addr':'Foo drive 23'},'Beth':{ 'phone':'9102','addr':'Bar street 42'},'Cecil':{ 'phone':'3158','addr':'Baz avenue 90'}}labels={ 'phone':'phone number','addr':'address'}name = raw_input('Name: ')request=raw_input('Phone number(p) or address(a)?')if request=='p': key='phone'if request=='a': key='addr'if name in people: print "%s's %s is %s." % (name,labels[key],people[name][key])
练习3:
在练习2基础上,当输入的信息不存在时候,返回not available信息people={ 'Alice':{ 'phone':'2341','addr':'Foo drive 23'},'Beth':{ 'phone':'9102','addr':'Bar street 42'},'Cecil':{ 'phone':'3158','addr':'Baz avenue 90'}}labels={ 'phone':'phone number','addr':'address'}name = raw_input('Name: ')request=raw_input('Phone number(p) or address(a)?')key=requestif request=='p': key='phone'if request=='a': key='addr'person=people.get(name,{})label=labels.get(key,key)result=person.get(key,'not available')print "%s's %s is %s." % (name,label,result)
练习4
正则替换[import time]Dear [name]I would like to learn how to program. I hear you use the [language] language a lot…And is [email] your correct email address?[time.asctime()]import fileinput, re# Matches fields enclosed in square brackets:field_pat = re.compile(r'\[(.+?)\]')# We'll collect variables in this:scope = {}# This is used in re.sub:def replacement(match): code = match.group(1) try: # If the field can be evaluated, return it: return str(eval(code, scope)) except SyntaxError: # Otherwise, execute the assignment in the same scope... exec code in scope # ...and return an empty string: return 'delete rows'lines = []for line in fileinput.input(): lines.append(line)text = ''.join(lines)# Substitute all the occurrences of the field pattern:result=field_pat.sub(replacement, text)Lst=[]for i in result: Lst.append(i) if ''.join(Lst)=='delete rows': # print "hello" Lst=[] if i=='\n' and len(Lst)==1: Lst=[] elif i=='\n' and len(Lst)>1: print ''.join(Lst) Lst=[]print ''.join(Lst)
转载地址:http://zzqmi.baihongyu.com/