Python [4]-functions, python Functions

Source: Internet
Author: User

Python [4]-functions, python Functions
I. define functions

Define a function to usedefStatement, write the function name, parameters in parentheses, and colons in sequence:Then, write the function body in the indent block. The return value of the function isreturnStatement. If noreturnStatement. After the function is executed, the result is returned, but the result isNone..

def add(a,b):  return a+bprint add(1,2)

Pass can be used to define empty Functions

def nop():    pass

When defining a function, you must determine the function name and number of parameters;

If necessary, check the data type of the parameter. You can use built-in functions to check the data type.isinstanceImplementation.

Ii. function return values

The function body can be used internally.returnReturns function results at any time;

No function execution completedreturnStatement, automaticallyreturn None.

A function can return multiple values at the same time, which is essentially a tuple.

def test(a,b,rank):  c=a+rank  d=b+rank  return c,dc,d=test(2,3,5)print cprint dt=test(5,10,1)print t
Iii. Function Parameters

① Default parameters

def power(x,n=2):  r=1  while(n>0):    r=r*x    n=n-1  return rprint power(2)>>4print power(2,10)>>1024


Note the following when setting default parameters:

First, the required parameter is in the front, and the default parameter is in the back;

Second, default parameters must point to unchanged objects.

② Variable parameters

Variable parameters allow you to input 0 or any parameter. These variable parameters are automatically assembled into a tuple during function calling. When defining variable parameters, add a star number * Before the variable name *.

def sum(*numbers):  s=0  for x in numbers:    s=s+x*x  return sprint sum(1,2,3,4,5)>>>55


If the parameter is list or turple, you must add a star number before the variable name.

list=[1,2,3,4,5]print sum(*list)>>>55t=(1,2,3,4,5)print sum(*t)>>>55


③ Keyword Parameters

Keyword parameters allow you to input 0 or any parameters with parameter names. These keyword parameters are automatically assembled into a dict in the function.

def show(name,age,**param):  print "name",name,"age",age,paramshow('liu',20,city='beijing',job='teacher')dic={'city':'beijing','job':'teacher','home':'hubei'}show('zhang',30,**dic)


Note that the order of parameter definitions must be: mandatory parameters, default parameters, variable parameters, and keyword parameters.

④ Summary

The default parameter must use an immutable object. If it is a mutable object, a logic error occurs during running!

Pay attention to the syntax for defining variable parameters and keyword parameters:

  • *argsIs a variable parameter, and args receives a tuple;
  • **kwIs a keyword parameter, and kw receives a dict.

How to pass in the syntax of variable and keyword parameters when calling a function:

Variable parameters can be passed in directly:func(1, 2, 3), You can first assemble list or tuple, and then pass*argsInput:func(*(1, 2, 3));

Keyword parameters can be passed in directly:func(a=1, b=2)Dict can be assembled first, and then**kwInput:func(**{'a': 1, 'b': 2}).

Iv. Anonymous Functions

In python, the lambda keyword is used to define anonymous functions.

For example, sort the elements of a string set by length.

S = ['hello', 'World', 'a'] s. sort (key = lambda x: len (x) print s running result: ['A', 'Hello', 'World']


V. Function kerialization

Function colialization is to fix several parameters of a function, so as to generalize multiple functions of different meanings. This requires the built-in partial function of the functools module. For example:

From functools import partialdef addNumber (a, B): return a + baddNumber10 = partial (addNumber, 10) addNumber20 = partial (addNumber, 20) print addNumber10 (100) # Running result 110 print addNumber20 (100) # running result 120


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: 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.