Home >Backend Development >Python Tutorial >Read through Python custom functions and Python function return values in one article, with detailed examples
Function (function) is one of the core contents of python programming. This article mainly introduces the concept of Python custom functions and Python function return values related knowledge points. Python custom functionWhat is it? What is the function, how to define the function and how to call the Python function return value.
What isPython custom function
A function is an organized, reusable code segment used to implement a single or related function .
Function can improve the modularity of the application and the reuse rate of the code. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.
So how to customize the Python function
1. You can define a function with the function you want, the following is Simple rules:
2. The function code block starts with the def keyword, followed by the function identifier name and parentheses ().
3. Any incoming parameters and independent variables must be placed between parentheses. Parameters can be defined between parentheses.
4. The first line of statements of a function can optionally use a documentation string - used to store function descriptions.
5. The function content starts with a colon and is indented.
6.return [expression] Ends the function and optionally returns a value to the caller. Return without an expression is equivalent to returning None.
AboutPython custom functionsSyntax:
def functionname( parameters ): "函数_文档字符串" function_suite return [expression]
By default, parameter values and parameter names are matched in the order defined in the function declaration Get up.
Example
def printme( str ): "打印传入的字符串到标准显示设备上" print str return
So how to write a Python function return value?
return statement:
return statement [expression] exit function, optional Returns an expression to the caller. A return statement without parameter values returns None. The previous examples did not demonstrate how to return a numerical value. The following example will tell you how to do it:
#!/usr/bin/python # -*- coding: UTF-8 -*- # 可写函数说明 def sum( arg1, arg2 ): # 返回2个参数的和." total = arg1 + arg2 print "函数内 : ", total return total; # 调用sum函数 total = sum( 10, 20 );
The output result of the above example is:
函数内 : 30
The above is the detailed content of Read through Python custom functions and Python function return values in one article, with detailed examples. For more information, please follow other related articles on the PHP Chinese website!