Python FunctionsDefKeywordsDefinition.DefKeyword followed by a functionIdentifierName, followed by a pair of parentheses. Variable names can be included in parentheses, which end with a colon. Next is a statement, which is the function body.
1. No parameter functions (functions without parameters)
Code:
Run:
2. Functions with Parameters
Parameter: name of the parameter in the function (for example, A and B in the code below)
Real parameters: values provided for function calls (for example, X and Y in the code below)
2.1 functions with common parameters
Code:
Run:
2.2 functions with default parameters (B is the default parameter in the code below)
Code:
Run:
When the default parameter value is specified for the form parameter, you do not need to pass the value to the default parameter when calling the function. For example, in the code above, the Add function adds the values of X and Y when X and Y are passed to it. When only X is passed, it adds X to the default parameter value.
Note:Only those parameters at the end of the parameter table can have default parameter values. That is, you cannot declare a parameter with the default value when declaring a function parameter, and then declare a parameter without the default value.
Because the value assigned to the form parameter is assigned based on the position. For example,Def add (a, B = 1)
Is valid,Def add (a = 1, B)
Is invalid.
2.3 key parameter functions
Key Parameter: we use the parameter name (keyword) instead of the position to specify the real parameter for the function. This has two advantages: 1. You do not have to worry about the order of parameters. Using the function becomes simpler. 2. you can assign values to only the parameters we want.
Code:
Run:
3. If you want a function to return values, add them to the function.ReturnStatement
Code:
Run: