Python basic article "2nd": Python custom functions

Source: Internet
Author: User
Tags function definition

python functions

1. Function definition

Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function. Functions can improve the modularity of the application, and the reuse of the code. You already know that Python provides a number of built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions.

2. Definition

  • The function code block begins with a def keyword followed by the function identifier name and parentheses ().
  • Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
  • The first line of the function statement can optionally use the document string-for storing the function description.
  • The function contents begin with a colon and are indented.
  • Return[expression] End Function, optionally returning a value to the caller. Return without an expression is equivalent to returning no
    1 def functionname (parameters): 2    " Function _ Document string " 3    function_suite 4    return [Expressi

3. Syntax 

1 def functionname (parameters): 2    " " Function _ Document Description string ' ' 3    function_body 4    return [Expression]

4. Function calls

  Defines a function that gives the function a name, specifies the parameters contained in the function, and the code block structure. Once the basic structure of this function is complete, you can execute it from another function call defined by the function name, or directly from the Python prompt.

5. Function parameters

The following are the formal parameter types that can be used when calling a function:

    • Required Parameters
    • Named parameters
    • Default parameters
    • Indefinite length parameter

Required Parameters:

The required parameters must be passed into the function in the correct order. The number of calls must be the same as when declared.

 #   !/usr/bin/python  #  -*-Coding:utf-8-*-  #   writable function description    Printme (str):  "   print any incoming string   print   Str;  return   #      call the Printme function  printme ();  

traceback  (most recent call last):  file< Span class= "PLN" >  "test.py" , line 11, in <module>  Printme (); typeerror: Printme () 1 argument  (0  Given)             

Named parameters

Named arguments and function calls are closely related, and the caller determines the passed-in parameter value with the name of the parameter. You can skip arguments that do not pass or sequence the arguments, because the Python interpreter can match parameter values with the name of the argument.

Call the Printme () function with a named parameter:

 #   !/usr/bin/python  #  -*-Coding:utf-8-*-  #   writable function description    Printme (str):  "   print any incoming string   print   Str;  return   #   call the Printme function  printme (str =  " my string  );  
The result of the above example output:
My string

The following example shows that the order of named parameters is not important to show more clearly:

#!/usr/bin/python#-*-coding:utf-8-*- #Writable Function DescriptiondefPrintinfo (name, age):"print any passed-in string"   Print "Name:", name; Print " Age", age; return; #Call the Printinfo functionPrintinfo (age=50, name="Miki");
The above example output: Name:  mikiage  50

Default parameters

When a function is called, the value of the default parameter is considered to be the default value if it is not passed in. The following example prints the default age if age is not passed in:

#!/usr/bin/python#-*-coding:utf-8-*- #Writable Function DescriptiondefPrintinfo (name, age = 35 ):   "print any passed-in string"   Print "Name:", name; Print " Age", age; return; #Call the Printinfo functionPrintinfo (age=50, name="Miki");p rintinfo (name="Miki");
The above example output: Name:  mikiage  :  mikiage  35

Indefinite length parameter

You may need a function that can handle more arguments than was originally declared. These parameters are called indeterminate length parameters, and are not named when declared, unlike the above 2 parameters. The basic syntax is as follows:

def functionname ([Formal_args,] *var_args_tuple):   " Function _ document string "    function_suite   return [expression]

Variable names with an asterisk (*) will hold all unnamed variable arguments. Choose not to send more parameters can also. The following example:

#!/usr/bin/python#-*-coding:utf-8-*- #Writable Function DescriptiondefPrintinfo (arg1, *vartuple):"Print any parameters passed in"   Print "Output:"   Printarg1 forVarinchvartuple:Printvarreturn; #Call the Printinfo functionPrintinfo (10);p Rintinfo (70, 60, 50);
above example output: output: 706050 

6. Anonymous functions

Python uses lambda to create anonymous functions.

    • Lambda is just an expression, and the function body is much simpler than def.
    • The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.
    • The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.
    • Although the lambda function appears to be only a single line, it is not equivalent to a C or C + + inline function, which is designed to call small functions without consuming stack memory to increase operational efficiency.

Grammar

The syntax for a lambda function contains only one statement, as follows:

Lambda [Arg1 [, Arg2,..... argn]]:expression

Example

 #   !/usr/bin/python  #  -*-Coding:utf-8-*-  #   writable function description  sum = lambda  arg1, arg2:arg1 + arg2;  #   call the Sum function  print   "  , Sum (Ten, 20 print   "  , Sum (a)  
The result of the above instance output: The added value  is: the value After addition is:  40

Python basic article "2nd": Python custom functions

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.