Introduction to Python (v) Definition of function

Source: Internet
Author: User
Tags function definition ming

Definition of functions in Python
Start with Def, followed by the name of the function definition and ()) ' Define parameters in parentheses ' with a colon, and zoom, return ends
Such as:

 def  hello (ming):         print ming         

Pass parameters:

ming=[1,2,3]
Ming= "OK"
As shown above, the variable is of no type and can be a list of STR
Parameters are divided into

必备参数关键字参数默认参数不定长参数

Required Parameters:

 def  hello (ming):         print ming         return 调用函数hello();

Then there will be an error

Keyword parameters:

 def  hello (ming):         print ming         return 调用函数hello(ming="ok");

The output is OK.

Default function:

 def  hello (n,m=10):         print n         print m调用函数hello(n=20,m=20);hello(n=100

return value
N=20 m=20
n=100 m=10
Variable length parameter:

 def  hello (*args):         print args         return 调用函数hello(1);hello(1,2,3,4)

Output
1
1,2,3,4
Anonymous functions:

正常函数: def  hello (n,m):         print n*m匿名函数:lambda n,m:n*m

Multiple formal parameters:

 def  hello (a,*args,**kwargs):         print args         return 调用函数hello(1,2,3,4,n=1,m=2)

Output:
1
(2,3,4)
{N:1,m:2}
Higher order functions:

map是计算乘积的高阶函数def hello(x):    print x * xmap(hello,[1,2,3,4])输出相同:1,4,9,16reduce是计算累计的高阶函数def hi (x,y):    print x+yreduce(hi,[1,2,3,4])    输出同样一样:15

Sorted sorting is more used in higher-order functions.

n = [5,7,6,3,4,1,2] m = sorted(n)      print n[5, 7, 6, 3, 4, 1, 2] print m[1, 2, 3, 4, 5, 6, 7]
 A=dict(a=1,c=2,b=3,d=4)如果我们直接排序print(sorted(A))[‘a‘, ‘b‘, ‘c‘, ‘d‘] print(sorted(A.item(), key=lambda x:x[1]) )           [(‘a‘, 1), (‘b‘, 2), (‘c‘, 3), (‘d‘, 4)]按倒叙排序 print(sorted(A.item(), key=lambda x:x[1],reverse=True) )     [(‘d‘, 4), (‘b‘, 3), (‘c‘, 2), (‘a‘, 1)]

Introduction to Python (v) Definition of function

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.