Python学习笔记(1)——函数

Python学习笔记(1)——函数

摘要:

Python函数的相关用法:默认参数,多参数,可变参数,参数表达式

1、函数

#function and fucntion pointer
def myadd(a,b):
    return a+b
f = myadd
print(f(5,6))

2、默认参数

#fucntion default paremeter
def ilike(first,second = 'banana',third ='apple'):
    print('first is ',end = ' ')
    print(first,end = ',')
    print('second is ',end = ' ')
    print(second,end = ' ')
    print('and third is ',end = ' ')
    print(third)

#keyword arguments
def parrot(voltage,state='a stiff',action='voom',type='Norwegian Blue'):
    print("-- This parrot wouldn't",action,end = ' ')
    print("if you input",voltage,"volts throuth it.")
    print("--Lovely plumage,the",type)
    print("--It's",state,"!")
#参数相关    
parrot(voltage = 1000)
parrot(voltage=10000,action='nianyu')
# parrot(voltage = 333,'dead')    #参数未指明对应key
# parrot(110,voltage=220)    #不明参数
parrot(action='hehe',voltage=50) #参数顺序不重要

def function(a):
    pass
#function(0,a=0)    #多了一个参数

3、多参数

# 多参数
def cheeseshop(kind,*arguments,**keywords):
    print("--Do you have any",kind,"?")
    print("--I'm sorry,we're all out of",kind)
    for arg in arguments:
        print(arg)
    print('-'*40)
    keys = sorted(keywords.keys())
    for kw in keys:
        print(kw,":",keywords[kw])
# **参数,代表dictionary参数
cheeseshop("cheese","nianyu",shop="Tom") 
# *参数必须出现在**参数之前
# cheeseshop("cheese",shop="Tom","nianyu")

# 可变参数
def concat(*args,sep = '/'):
    print(sep.join(args))
concat("earth","mars","venus")
#earth/mars/venus
concat("earth","mars","venus",sep=".")
#earth.mars.venus


# 取出参数列表
print(list(range(3,6)))
#[3, 4, 5]
args = [3,6]
print(list(range(*args)))
#[3, 4, 5]

4、表达式函数

#表达式函数Lambda Expressions
#返回一个函数
def make_incrementor(n):
    return lambda x : x+n
f = make_incrementor(42)
print(f(0))
#41
f = make_incrementor(65)
print(f(1))
#66

#传递一个lambda表达式函数座位参数
pairs = [(3,'three'),(2,'two'),(1,'one')]
pairs.sort(key=lambda pair:pairs)
print(pairs)
#[(3, 'three'), (2, 'two'), (1, 'one')]

5、函数注释

#源码注释文档
def my_func():
    '''
    This is my function
    parameter: None
    return   : None
    '''
    pass

help(list)





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值