博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python小练习
阅读量:4221 次
发布时间:2019-05-26

本文共 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/

你可能感兴趣的文章
初见成效
查看>>
于根伟退役了。。
查看>>
大年初一的晚上
查看>>
接近尾声咯
查看>>
。。。。。。。。。。
查看>>
你还是杀了我吧
查看>>
这个旋律。。
查看>>
这些是我没有好好珍惜的。。
查看>>
2006年2月9日 凌晨0点46分
查看>>
技术文章
查看>>
最近要拿下treeview的第三方控件
查看>>
BBS的完善
查看>>
郁闷了。。。
查看>>
差不多了。。
查看>>
再接下来。。。
查看>>
怎么能正常显示多行文本呢?
查看>>
下一话题。。。
查看>>
这段话有啥用呢??
查看>>
COALESCE
查看>>
CAST
查看>>