01. function parameters and return values
FunctionAre there any parameters?AndReturn Value?, YesCombination, A totalFour TypesCombination form
- No parameter, no return value
- No parameter, Return Value
- There are parameters and no return values
- Parameters and returned values
When defining a function,Whether to receive parameters or whether to return resultsIs based onActual functional requirementsTo decide!
- If the FunctionUncertain data processed internallyTo pass external data to the function as parameters.
- If you want a functionReport the execution results to the outside worldTo increase the return value of the function.
1.1 No parameter, no return value
This type of function does not receive parameters or return values. The application scenario is as follows:
- Just do one thingFor exampleDisplay menu
- Inside the FunctionPerform operations on global variablesFor example:New business card, Final resultRecorded in global variablesMedium
Note:
- If the data type of the global variable isVariable typeWhich can be used inside the FunctionMethodModify the content of global variables --Variable reference will not change
- Inside the function,Use the value assignment statementYesModify variable references
1.2 No parameter, Return Value
Such functions do not receive parameters but return values. The application scenario is as follows:
- Collect data, suchThermometerThe returned result is the current temperature without passing any parameters.
1.3 There are parameters and no return values
This type of function receives parameters and does not return values. The application scenario is as follows:
- The internal code of the function remains unchanged.Different parameters process different data
1.4 There are parameters and return values
Such functions receive parameters and return values. The application scenario is as follows:
- The internal code of the function remains unchanged.Different parameters process different dataAndReturn the expected processing result
02. function return value
- In program development, sometimesAfter a function is executed, the caller is notified of a result.So that the caller can follow up on the specific results
- Return ValueYes FunctionComplete the workAfter,LastTo the callerOne result
- Use in Functions
return
Keyword can return results
- The caller canUse VariablesComeReceiveFunction return result
Q: Can I return multiple results after a function is executed?
Example-Temperature and Humidity Measurement
- Suppose we want to develop a function that can return both the current temperature and humidity.
- First complete the return temperatureThe functions are as follows:
Def measure (): "Return Current temperature" Print ("START measurement... ") temp = 39 print (" Measurement ends... ") return tempresult = measure () print (result)
- Under ExploitationTuplesThe returned temperature can also be returned.Humidity
- The transformation is as follows:
Def measure (): "Return Current temperature" Print ("START measurement... ") temp = 39 wetness = 10 print (" Measurement ends... ") Return (temp, wetness)
Tip: If a function returns a tuples, parentheses can be omitted.
- In
Python
, You canConvert a tupleUseAssignment StatementAlso assignedMultiple variables
- Note: The number of variables must be consistent with the number of elements in the element group.
result = temp, wetness = measure()
Expansion: Exchange two numbers
- There are two Integer Variables
a = 6
,b = 100
- Do not use other variables,Exchange the values of two variables
Solution 1 -- use other variables
# Solution 1-use the Temporary Variable c = BB = AA = C
Solution 2 -- do not use temporary variables
# Solution 2-do not use the temporary variable A = a + BB = A-BA = A-B
Solution 3 -- Python proprietary, using tuples
a, b = b, a
03. function parameters 3.1. immutable and mutable Parameters
Question 1: Inside the function, useAssignment StatementWill it affect the information passed when calling the function?Real Variable? -- No!
- Regardless of the ParameterVariableOrImmutable
- As longFor ParametersUseAssignment Statement, WillFunction internalModifyLocal variable reference,Does not affect external variable reference
Def demo (Num, num_list): Print ("internal function") # value assignment statement num = 200 num_list = [1, 2, 3] print (Num) print (num_list) print ("Function Code completed") gl_num = 99gl_list = [4, 5, 6] demo (gl_num, gl_list) print (gl_num) print (gl_list)
Question 2: If the passed parameter isVariable typeIn the function, useMethodModified the data content,It also affects external data.
def mutable(num_list): # num_list = [1, 2, 3] num_list.extend([1, 2, 3]) print(num_list)gl_list = [6, 7, 8]mutable(gl_list)print(gl_list)
Expansion:
+=
- In
python
List variable call+=
In essence, the list variable is executed.extend
Method, does not modify the reference of the Variable
Def demo (Num, num_list): Print ("internal function code") # num = num + = num # num_list.extend (num_list) because it is a call method, so the reference of the variable will not be modified # After the function is executed, the external data will also change num_list + = num_list print (Num) print (num_list) print ("Function Code completed ") gl_num = 9gl_list = [1, 2, 3] demo (gl_num, gl_list) print (gl_num) print (gl_list)
3.2 default parameters
- When defining a function, you canA PARAMETERSpecifyDefault ValueThe parameter with the default value is calledDefault Parameter
- IfDefault ParameterIs specified when the function is defined internally.Default Value
- The default parameter of the function,Set common values to the default values of parameters.ToSimplify function calls
- For example, sort the list
Gl_num_list = [6, 3, 9] # by default, it is sorted in ascending order, because this application requires more gl_num_list.sort () print (gl_num_list) # Only when descending order is required, to pass the 'reverse' parameter gl_num_list.sort (reverse = true) print (gl_num_list)
Specify the default parameters of the function.
- Use the value assignment statement after the parameter to specify the default value of the parameter.
Def print_info (name, gender = true): gender_text = "boys" if not gender: gender_text = "girls" Print ("% s is % s" % (name, gender_text ))
Prompt
- Default parameter, which must be usedThe most common valueAs the default value!
- If the value of a parameterUncertain, You should not set the default value. The specific value is passed by the outside world when the function is called!
Note for default parameters 1) location defined by default parameters
- Must be guaranteed Default parameters with default values At the end of the parameter list
- Therefore, the following definition is incorrect!
def print_info(name, gender=True, title):
2) call a function with multiple default parameters
- InWhen calling a function, IfMultiple default parameters,Parameter name must be specifiedIn this way, the interpreter can know the corresponding relationship of parameters!
Def print_info (name, title = "", Gender = true): ": Param title: Position: Param name: name of the class: Param gender: true boys false girls "gender_text =" boys "if not gender: gender_text =" girls "Print (" % S % s is % s "% (title, name, gender_text) # tip: when specifying the default value of the default parameter, use the most common value as the default value! Print_info ("Xiao Ming") print_info ("Lao Wang", Title = "") print_info ("Xiaomei", Gender = false)
3.3 Multi-value Parameter definition functions that support multi-value Parameters
- Sometimes you may needA functionParameters that can be processedNumberIt is not certain. You can use it at this time.Multi-value Parameter
python
InTwo TypesMulti-value parameter:
- Add before parameter nameOne
*
YesTuples
- Add before parameter nameTwo
*
YesDictionary
- Generally, when naming a multi-value parameter,HabitsUse the following two names:
*args
-- StorageTuplesParameter.*
**kwargs
-- StorageDictionaryParameter. There are two*
args
Yesarguments
Meaning of a Variable
kw
Yeskeyword
Abbreviation,kwargs
MemorableKey-Value Pair Parameters
Def demo (Num, * ARGs, ** kwargs): Print (Num) print (ARGs) print (kwargs) demo (1, 2, 3, 4, 5, name = "James", age = 18, Gender = true)
Tip:Multi-value ParameterApplications will often appear in some development frameworks on the internet, knowing the multi-value parameters,This helps us understand the code of Daniel.
Multi-value parameter case -- calculate the sum of any number
- Define a function
sum_numbers
, Can receiveAny number of Integers
- Function requirements:Add all numbersAnd the accumulative result is returned.
Def sum_numbers (* ARGs): num = 0 # sum the Order of The args tuples for N in ARGs: num + = n return numprint (sum_numbers (1, 2, 3 ))
Unpacking of tuples and dictionaries
- When calling a function with multi-value parameters, If You Want:
- SetTuples, Directly transmitted
args
- SetDictionary variable, Directly transmitted
kwargs
- You can useUnpackingTo simplify parameter transmission,UnpackingThe method is:
- InBefore the tuples, AddOne
*
- InBefore dictionary Variables, AddTwo
*
Def demo (* ARGs, ** kwargs): Print (ARGs) print (kwargs) # You need to pass a tuples/dictionary variable to the function's corresponding parameter gl_nums = (1, 2, 3) gl_xiaoming = {"name": "Xiao Ming", "Age": 18} # Use num_tuple and Xiaoming as tuples to pass ARGs # demo (gl_nums, gl_xiaoming) demo (* gl_nums, ** gl_xiaoming)
04. recursion of functions
Function callsProgramming SkillsCalled Recursion
4.1 features of recursive functions
Features
- A function Internal Call yourself
- Other functions can be called within the function, and you can also call yourself within the function.
Code features
- FunctionCodeIs the same, onlyParametersDifferent,Different processing results
- WhenThe parameter meets one condition.The function is no longer executed.
- This is very importantIs usually called the exit of recursion. OtherwiseAn endless loop occurs.!
Sample Code
Def sum_numbers (Num): Print (Num) # recursive exit is very important. Otherwise, an endless loop if num = 1: Return sum_numbers (Num-1) sum_numbers (3) appears)
4.2 recursive case -- Calculating the number Accumulation
- Define a function
sum_numbers
- Can receive
num
Integer Parameter
- Calculate the result of 1 + 2 +... num
Def sum_numbers (Num): If num = 1: return 1 # assume that sum_numbers can accumulate num-1 temp = sum_numbers (Num-1) # The core algorithm inside the function is the addition of two numbers return num + tempprint (sum_numbers (2 ))
07 _ function Advanced