Python functions
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.
Define a function
You can define a function that you want to function, and here are the simple rules:
- 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] ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.
Grammar
def functionname (Parameters): " Function _ Document string " # functionname function name function_suite return [expression]
View Code
By default, parameter values and parameter names are matched in the order defined in the function declaration.
Function call
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 or directly from the Python prompt.
The following instance calls the Printme () function:
#!/usr/bin/python#-*-coding:utf-8-*- #Defining Functionsdefprintme (str):"print any passed-in string" Printstr; return; #calling FunctionsPrintme"I want to invoke the user custom Function!");p Rintme ("call the same function again");
Python Basics-Functions