python 函数的参数

函数的参数类型有:位置参数,默认参数,可变参数,关键字参数,命名关键字参数

1.位置参数

def power(x):
    return x*x

power(1)
1
power(2)
4
power(0)
0

2.默认参数:默认参数必须指向不可变对象

def power(x,n=2):
    sum=1
    while n>0:
        n=n-1
        sum=sum*x
    return sum


power(1)
1
power(2)
4
power(2,3)
8

3.可变参数

def calcs(*nums):
    sum=0
    for num in nums:
        sum=sum+num
    return sum

calcs(1,2,3,4,5)
15
l=[1,2,3,4,5]
calcs(*l)
15
t=(1,2,3,4,5)
calcs(*t)
15

4.关键字参数

def person(name,age,**kw):
    print("name:",name,"age:",34,"others:",kw)

person("zhou hailong",23,city="suzhou",scores=99)
name: zhou hailong age: 34 others: {'city': 'suzhou', 'scores': 99}


others={"city":"suzhou","scores":99}

person("zhou hailong",24,city=["city"],scores=["scores"])
name: zhou hailong age: 34 others: {'city': ['city'], 'scores': ['scores']}

person("zhou hailong",25,**others)
name: zhou hailong age: 34 others: {'city': 'suzhou', 'scores': 99}

5.命名关键字参数

def person(name,age,*,city,scores):
    print("name:",name,"age:",age,city,scores)

    
person("zhou hailong",24,city="suzhou",scores=88)
name: zhou hailong age: 24 suzhou 88


person("zhou hailong",24,city="suzhou",num=22)
Traceback (most recent call last):
  File "<pyshell#315>", line 1, in <module>
    person("zhou hailong",24,city="suzhou",num=22)
TypeError: person() got an unexpected keyword argument 'num'

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值