07 _ function Advanced

Source: Internet
Author: User
01. function parameters and return values

FunctionAre there any parameters?AndReturn Value?, YesCombination, A totalFour TypesCombination form

  1. No parameter, no return value
  2. No parameter, Return Value
  3. There are parameters and no return values
  4. Parameters and returned values

When defining a function,Whether to receive parameters or whether to return resultsIs based onActual functional requirementsTo decide!

  1. If the FunctionUncertain data processed internallyTo pass external data to the function as parameters.
  2. 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:

  1. Just do one thingFor exampleDisplay menu
  2. 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 FunctionsreturnKeyword 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.

  • InPython, 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
  1. There are two Integer Variablesa = 6,b = 100
  2. 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: +=
  • InpythonList variable call+=In essence, the list variable is executed.extendMethod, 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

  1. Default parameter, which must be usedThe most common valueAs the default value!
  2. 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
  • pythonInTwo 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*
  • argsYesargumentsMeaning of a Variable
  • kwYeskeywordAbbreviation,kwargsMemorableKey-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
  1. Define a functionsum_numbers, Can receiveAny number of Integers
  2. 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 transmittedargs
    • SetDictionary variable, Directly transmittedkwargs
  • 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

  1. FunctionCodeIs the same, onlyParametersDifferent,Different processing results
  2. 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
  1. Define a functionsum_numbers
  2. Can receivenumInteger Parameter
  3. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.