python语法31[函数]


一 简单函数和函数指针
def  myadd(a,b):
    
return  a  +  b;

print (myadd( 3 , 2 ));
=  myadd;
print (f( 20 , 30 ));

二 函数的默认参数
def  result(r  =   2 ):
    
if ( r  ==   1 ):
        
print ( ' bad ' )
    
elif (r  ==   2 ):
        
print ( ' good ' )
    
elif (r  ==   3 ):
        
print ( ' great ' )

result()
result(
1 )

def  f2(a, L = []):
    L.append(a)
    
return  L

print (f2( 1 ))
print (f2( 2 ))
print (f2( 3 ))

def  f3(a, L = None):
    
if  L  is  None:
        L 
=  []
    L.append(a)
    
return  L

print (f3( 1 ))
print (f3( 2 ))
print (f3( 3 ))
结果:
good
bad
[1]
[1, 2]
[1, 2, 3]
[1]
[2]
[3]
注意:
默认值在程序的整个运行过程中仅评估一次,对于参数为可变类型的要特别注意,例如list,dictionary,大部分的class类型。
跟C++一样,没有默认值的在前,后面的为有默认值。

三 关键字参数和参数打包
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)

ilike(
' pear ' );
ilike(
' pear ' , second  =   ' apple ' , third  =   ' banana ' )
ilike( 
' ilike ' , third  =   ' god ' )

=  { ' third '  :  ' apple ' ' second '  :  ' pear ' " first "  :  " banana " }
ilike(
** d)


四 任意长度参数和dictionary参数
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])

cheeseshop(
" Limburger " " It's very runny, sir. " ,
           
" It's really very, VERY runny, sir. " ,
           shopkeeper
= " Michael Palin " ,
           client
= " John Cleese " ,
           sketch
= " Cheese Shop Sketch " )
注意:
*参数名字,表示任意个数的参数。
**参数名字,表示dictionary参数。
*参数必须出现在**前面。

五 函数定义lamda表达式
def  make_incrementor(n):
     
return   lambda  x: x  +  n

=  make_incrementor( 42 )
print (f( 1 ))
print (f( 2 ))
注意:这功能高级!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值