程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Follow the turtle up master to learn Python - function (2)

編輯:Python

Parameters : Positional arguments 、 Key parameters 、 Default parameters

Positional arguments : take Python The parameter with fixed position in is called position parameter .

>>> def myfunc(s, vt, o):
    return ''.join((o, vt, s))

>>> myfunc(' I ', ' I hit ', ' Little turtle ')
' Little turtle hit me '
>>> myfunc(' Little turtle ', ' I hit ', ' I ' )
' I shot a little turtle '

Key parameters : In the case of many parameters , Remembering parameter positions is a bit annoying , You can use keyword parameters to solve problems .

>>> myfunc(o=' I ', vt=' I hit ', s=' Little turtle ')
' I shot a little turtle '
>>> myfunc(o=' I ',' Steamed ', ' Little turtle ')
SyntaxError: positional argument follows keyword argument

Rules when positional parameters and keyword parameters are used at the same time , The location parameter must precede the keyword parameter .

Default parameters : Allow function parameters to specify default values when they are defined , And the default value should be placed at the end . If you reassign , You can replace the default value .

>>> def myfunc(s, vt, o=' Little turtle '):
    return ''.join((o, vt, s))

>>> myfunc(' Banana ', ' eat ')
' Little turtle eats bananas '
>>> myfunc(' Banana ', ' eat ', ' monkey ')
' Monkeys eat bananas '

>> def myfunc(s=' Apple ', vt, o=' Little turtle '):
    return ''.join((o, vt, s))
SyntaxError: non-default argument follows default argument                  // The default parameter should be placed at the end
>>> def myfunc(vt, s=' Apple ', o=' Little turtle '):
    return ''.join((o, vt, s))

>>> myfunc(' Arched ')
' The little turtle arched the apple '

Cold knowledge :/ and *

The parameter to the left of the slash must be a positional parameter , It cannot be a keyword parameter .

To the left of the asterisk can be either a position parameter , It can also be a keyword parameter , The right side must be a keyword parameter .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved