Function is an organized, reusable code segment used to implement a single or related function.
Custom functions basically have the following rules and steps:
The function code block starts with the def keyword, followed by the function identifier name and parentheses ()
Any incoming parameters and independent variables must be placed between parentheses. The first line of statements between parentheses can be used to define parameters
The first line of the function can optionally use a documentation string (used to store function descriptions)
The function content starts with a colon, and Indent
return [expression] Ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.
Syntax example:
def functionname( parameters ): "函数_文档字符串" function_suite return [expression]
Example:
def Define a function, given a function name sum
Declare two parameters num1 and num2
The first line of the function describes the function: the sum of the two numbers
The final return statement ends the function and returns the sum of the two numbers
def sum(num1,num2): "两数之和" return num1+num2 # 调用函数 print(sum(5,6))
Output result:
11Next Section