Functions of Python

Source: Internet
Author: User

1. What is a function?

There are two variables x and y, and when x takes each specific value in its range of changes, the corresponding unique y corresponds to it, and Y is the function of X. Remember y = f (x), where x is the argument and y is the dependent variable.

The function is composed of three parts:

x: Input, the general function can have more than one input.
F:function, it is this method to convert X to y,function in a specific way.
Y: output, the general function has only one output, the function in computer technology can also not output.

<p id= the function of "div-border-left-red" >python: consists of several statement blocks (functions), function names, parameter lists (inputs) to complete a function (output). </p>

2. Definition and invocation of functions 1. Definition of function

Python defines functions using DEF statements

def 函数名(参数列表):    函数体(代码块)    [return 返回值]

Function Name: General naming requirements.
Parameter list: Place a marker placeholder, called <font color= #DC143C > Parameters </font>.
Function Body: A block of code that determines the parameters of a function.
Return: The return statement is used by default and none is returned without default.

2. Invocation of functions

By invoking the function name defined earlier, you can run the function to get the return value of the function.
Attention:
When calling, you need to enclose the function name with parentheses () in parentheses () to fill in the required parameters in the function body, and the incoming parameters are called <font color= #DC143C > Arguments </font>.
The parameters passed in by the function must be in the same quantity as the required functions (arguments) in the function body, unless there are default parameters defined in the original function argument list.

#定义函数add()def add(x,y):    sum = x+y    return sum#调用函数add()add(1,3)
4
3. Parameters of the function

The parameters that are passed into the python are divided into two categories, one of which is called positional parameters, and another parameter that can be passed in according to the parameters defined by the parameter is called the keyword parameter.
When passing in, positional parameters need to be placed before the keyword parameter.

1. General position Parameters

Give the parameter 1 to x, and the parameter 3 to Y. One by one corresponds, this is the positional parameter. The positional parameters are passed in in order one by one.

def add(x,y):    sum = x+y    return sumadd(1,3)  
4
2. Variable position parameters

Add "*" in front of normal position to accept multiple parameters at once. Multiple arguments are collected using one tuple (tuple).

def add(*nums):    sum = 0    print(type(nums))    for x in nums:        sum+=x    print(sum)add(3,5,6)
<class ‘tuple‘>14

<div class= "Note danger No-icon" ><p> Description: In general, if the normal parameters and variable position parameters are fixed together, the normal parameters need to be placed before the positional parameters. </p></div>

def add(x,*nums):    sum = 0    print(nums)    for x in nums:        sum+=x    print(sum)add(3,5,6)
(5, 6)11
3. Keyword parameters

Pass 3 to y,1 to X. Follow the defined keywords to pass in the parameters, the location can be arbitrary.

def add(x,y):    sum = x+y    
4

<div class= "Note danger No-icon" ><p> Description: When the positional parameters and keyword parameters are passed in together, the positional parameters need to be placed in front of the keyword parameters. </p></div>

def add(x,y):    sum = x+y    
2
4. Variable keyword parameters

Add two "* *" before the normal keyword parameter, you can accept more than one keyword parameter at a time, the name and value of the collected argument form a dictionary (dict).

def showconfig(**kwargs):    for k,v in kwargs.items():        print(‘{} = {}‘.format(k, v))showconfig(host=‘127.0.0.1‘,port=‘8080‘,username=‘mykernel‘,password=‘qwe123‘)
username = mykernelpassword = qwe123port = 8080host = 127.0.0.1

<div class= "Note danger No-icon" ><p> Description: When a variable parameter is defined with a normal parameter, the variable parameter needs to be placed after the normal parameter. </p></div>

def showconfig(x,y,*args,**kwargs):        print(x)        print(y)        print(args)        print(kwargs)showconfig(‘127.0.0.1‘,8080,‘mykernel‘,password=‘qwe123‘)#此时使用关键字参数给x,y赋值就会报错。
127.0.0.18080(‘mykernel‘,){‘password‘: ‘qwe123‘}
5. Default parameters

Some parameters are rarely changed, so you can pass in a default value when you specify a parameter, and the new parameter takes effect when a new argument is replaced.
The default parameter must be placed after the normal parameter

#传入默认值参数def add(x=11,y=111):    sum = x+y    return sumadd() #未传入参数,默认参数生效
122
#有再次传入参数,替换默认值。def add(x=11,y=111):    sum = x+y    return sumadd(657,y=123) #新传入的参数生效
780

Define a function login with parameter names called host, port, username, and password.

def login(host=‘127.0.0.1‘,port=‘80‘,username=‘mykernel‘,password=‘123‘):    print(‘{}:{}\nname:{}\npasswd:{}\n‘.format(host,port,username,password))login()login(‘192.168.1.1‘,8080)login(‘10.0.0.1‘,password=‘qwe123‘)
127.0.0.1:80name:mykernelpasswd:123192.168.1.1:8080name:mykernelpasswd:12310.0.0.1:80name:mykernelpasswd:qwe123
6.keyword-only parameters (introduced after Python3)

define method One: after the variable position parameter, the normal parameter appears. At this point, this common parameter is considered as the keyword-only parameter by Python, and the keyword-only parameter must be passed in by using the keyword pass method when it is passed in.

definition Method Two:def fn (*, x, y), *, followed by common parameters, also considered as keyword-only parameters, and x, y are keyword-only parameters.

7. Parameter definition Order

The general order of <div class= "note danger no-icon" ><p> parameter list is: normal parameter, default parameter, variable position parameter, keyword-only parameter (with default value), variable keyword parameter. </p></div>

def fn1(x, y, z=3, *args, m=4, n, **kwargs):    print(x,y)    print(z)    print(args)    print(m,n)    print(kwargs)    print(end=‘\n‘)#x,y是普通参数#z,带默认值,传入时候省略,缺省参数#*args,可变位置参数#m=4,keyword-only 缺省参数#n,keyword-only参数#**kwargs,可变关键字参数fn1(1,2,n=4)fn1(1,2,4,43,123,k=123,m=11,n=13,j=‘hello‘)
1 23()4 4{}1 24(43, 123)11 13{‘j‘: ‘hello‘, ‘k‘: 123}
def fn2(x, y, z=3, *, m=4, n, **kwargs):  #定义m,n为keyword-only参数。    print(x,y)    print(z)    print(m,n)    print(kwargs)    print(end=‘\n‘)fn2(1,2,m=1,n=2)
1 231 2{}
8. Parametric deconstruction
def add(x,y):    print(x+y)    print()add(*(4,6)) #参数解构# add(*(1,2)) add(*[1,2]) add(*{1,3}) add(**{‘x‘:1,‘y‘:11}) #字典参数解构,x,y参数要和定义的对应起来。把x=1,y=11 传入形参,关键字传参。d = {‘a‘:1,‘b‘:12}add(*d.keys()) #取k 把取出来的k赋值给形参,位置传参。add(*d.values()) #取values
1012ab13

Promotion Blog: http://hexo.mykernel.cn/python-function-1.html

Functions of Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.