零基础入门Python3-函数详解(2)

昨天我们讲到了函数的位置参数和默认参数。今天继续讲解可变参数、关键字参数和命名关键字参数。

 

1、可变参数

可变参数就是参数的数量是不固定的,可以是 0 个,也可以是更多。比如说,你有些什么兴趣爱好?可能有游泳、唱歌、跳舞、编程...,但是也有可能只喜欢编程。所以在这种情况下,我们使用可变参数来传递这些值。

# 实例1,请写出你的兴趣爱好

my=['changge','tiaowu','youyong','biancheng','xiezuo']

def func(xq):

for i in xq:

print('I like:{0}'.format(i))

func(my)

>>>    

    I like:changge

    I like:tiaowu

    I like:youyong

    I like:biancheng

    I like:xiezuo

 

# 实例2, 我的兴趣只有编程和写作

my=['biancheng','xiezuo']

def func(xq):

for i in xq:

print('I like:{0}'.format(i))

func(my)

>>>    

    I like:biancheng

    I like:xiezuo

# 解决办法

def 函数名(*参数):    # 参数前面加个 * ,则表示可变参数

            语句1

            语句2

            ......

# 调用函数

函数名(v1,v2,v3,......)    #调用函数时,直接输入参数就可以了,不用赋值 list 和 tupe

 

# 实例1

def func(*xq):

for i in xq:

print('you like '+i)

 

func('changge','tiaowu','xiezuo','biancheng')

>>>    

    you like changge

    you like tiaowu

    you like xiezuo

    you like biancheng

# 如果已经有 list 和 tuple 的话,也是可以直接在变量前面加 *

# 实例1

a=(1,3,5,7,9)

def func(*num):

sum=0

for i in num:

sum=sum+i*i

print(sum)

        return None

func(*a)

>>>    165

 

# 实例2,位置参数+默认参数+可变参数的应用

def func(name,age,*xq,sex='boy'):

print('My name is {0},i am {1} years old,I am a {2}.'.format(name,age,sex))

for i in xq:

print('I like '+i)

        return None

 

func('zhangsan',27,'biancheng','changge','youyong')

>>>        My name is zhangsan,i am 27 years old,I am a boy.

               I like biancheng

               I like changge

               I like youyong

# 把默认参数放到最后,是防止 * xq的值覆盖掉

 

2、关键字参数

关键字参数,可以扩展函数的参数。比如,我们在做用户注册时,我们只提供了用户名、密码、邮箱这几个选项。但是用户还能提供注册地址、注册时间、用途等。当然这些相对来说都是可选项。

def 函数名(**参数名):    # 关键字参数必须是 dict

        语句1

        语句2

        ......

# 函数的调用

函数名(**变量)    # **变量为 key='值'

# 实例1

def func(**k):

print(type(k),k)

func(k1='value1',k2='value2')

>>>    <class 'dict'> {'k1': 'value1', 'k2': 'value2'}

# 实例2

a={'from':'Beijing','time':20181201}

def func(username,password,Email,**other):

print('zhu ce xin xi:')

print('Username:'+username)

print('Password:'+password)

print('Email:'+Email)

print(other)

return None

func('zhangsan','666666','123456@qq.com',**a)

>>>    zhu ce xin xi:

          Username:zhangsan

          Password:666666

          Email:123456@qq.com

          {'from': 'Beijing', 'time': 20181201}

# 当有dict时,调用函数直接在变量前加 **

关注公众号,了解更多!

转载于:https://www.cnblogs.com/pyshadow/p/10400302.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值