2018-07-28

可变参数的设置:args

#!/usr/bin/env python3

... #-*-coding:utf-8-*-

...

>>> def hello(greeting,*args):

...    if (len(args)==0):

...        print('%s!' % greeting)

...    else:

...        print('%s, %s!' % (greeting, ','.join(args)))

...

>>> hello('Hi')# =>greeting='Hi',args=()

Hi!

>>> hello('Hi','Sarah')# =>greeting='Hi',args=('Sarah')

Hi, Sarah!

>>> hello('Hello','Michael','Bob','Adam')#=>greeting='Hello',args=('Michael','Bob','Adam')

Hello, Michael,Bob,Adam!

>>>

>>> names = ('Bart','Lisa')

>>> hello('Hello',*names) #=>greeting='Hello',args=('Bart','Lisa')

Hello, Bart,Lisa!



关键字参数  **kw

第一种:

#!usr/bin/env python3

... #-*-coding:utf-8-*-

...

>>> def print_scores(**kw):

...    print('Name score')

...    print('.........')

...    for name, score in kw.items():

...        print('%10s %d' % (name,score))

...    print()

...

>>> print_scores(Adam=99, Lisa=88, Bart=77)

Name score

.........

      Adam 99

      Lisa 88

      Bart 77

第二种:

data = {

...    'Adam Lee':99,

...    'Lisa S' : 88,

...    'F.Bart' : 77

... }

print_scores(**data)

Name score

.........

  Adam Lee 99

    Lisa S 88

    F.Bart 77

第三种:

def print_info(name,*,gender,city='Beijing',age):

...    print('personal Info')

...    print('........')

...    print('Name: %s' % name)

...    print('Gender: %s' % gender)

...    print('City: %s' % city)

...    print('Age: %s' % age)

...    print()

...

>>> print_info('Bob',gender='male',age=20)

personal Info

........

Name: Bob

Gender: male

City: Beijing

Age: 20

>>> print_info('Lisa',gender='female',city='Shanghai',age=18)

personal Info

........

Name: Lisa

Gender: female

City: Shanghai

Age: 18

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Python 是一种相当高级的语言,通过 Python 解释器把符合语法的程序代码转换成 CPU 能够执行的机器码...
    Python程序媛阅读 2,049评论 0 3
  • 基础1.r''表示''内部的字符串默认不转义2.'''...'''表示多行内容3. 布尔值:True、False(...
    neo已经被使用阅读 1,889评论 0 5
  • 递归函数以及尾递归优化: #利用递归函数计算阶乘 ... #N! = 1 * 2 * 3 * 4 * ... * ...
    淡水t海边阅读 163评论 0 0
  • 工作方面 11月又快到月中了,这周基本忙于工作。 每个地方都要去督查,说来还是自己在考核方面不忍心,导致成系统数据...
    走向阳光的自己阅读 434评论 0 2
  • 今天早起精神不振,老公早上出门上班没察觉到我的低落状态亲昵地拍拍我,我格外厌烦。出门伞坏了……糟了,一连串负面事件...
    天蓝蓝47阅读 216评论 0 0

友情链接更多精彩内容