美文网首页
2018-07-28

2018-07-28

作者: 淡水t海边 | 来源:发表于2018-07-29 09:57 被阅读0次

    可变参数的设置: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

    相关文章

      网友评论

          本文标题:2018-07-28

          本文链接:https://www.haomeiwen.com/subject/tbqamftx.html