python小练习

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=request
if 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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值