study Python 27day

#for ... else...
for i in [1,2,3,4]:
    print(i)
else:
    print(i,'我是else')

for i in [1,2,3,4]:
    if i>2:
        print(i)
else:
    print(i,"我是else")


#一颗星(*)和两颗(*)
def multi_sum(*args):
    s=0
    for item in args:
        s+=item
    return s
print(multi_sum(3,4,5))

def do_something(name, age, gender='男', *args, **kwds):
    print('姓名:%s,年龄:%d,性别:%s'%(name, age, gender))
    print(args)
    print(kwds)
print(do_something('xufive', 50, '男', 175, 75, math=99, english=90))

a=(1,2,3)
print(*a)

c = {'name':'xufive', 'age':51}
print('name:{name}, age:{age}'.format(**c))

#三元表达式
y=5
x=-1 if y<0 else 1
print(x)

#with  as
'''fp = open(r"D:\CSDN\Column\temp\mpmap.py", 'r')
try:
    contents = fp.readlines()
finally:
    fp.close()

with open(r"D:\CSDN\Column\temp\mpmap.py", 'r') as fp:
    contents = fp.readlines()
'''
#列表推导式
a=[1,2,3,4]
result=[i*i for i in a]
print(result)

#列表索引的各种骚操作
a=[0,1,2,3,4,5]
b=['a','b']
a[2:2]=b

#lambda
lambda x,y:x+y

a=[1,2,3]
for item in map(lambda x:x*x,a):
    print(item ,end=',')

#yield生成器(一次性迭代器)
def get_square(n):
    for i in range(n):
        yield(pow(i,2))

#装饰器
import time
def timer(func):
    def wrapper(*args,**kwds):
        t0 = time.time()
        func(*args,**kwds)
        t1 = time.time()
        print('耗时%0.3f'%(t1-t0,))
    return wrapper
@timer
def do_something(delay):
    print('函数do_something开始')
    time.sleep(delay)
    print('函数do_something结束')

#巧用断言assert
def i_want_to_sleep(delay):
    assert(isinstance(delay, (int,float))), '函数参数必须为整数或浮点数'
    print('开始睡觉')
    time.sleep(delay)
    print('睡醒了')
发布了65 篇原创文章 · 获赞 0 · 访问量 546

猜你喜欢

转载自blog.csdn.net/u011624267/article/details/103987838