Python foundation function

Time:2020-2-13

function

What is a function

Function is a tool that can be called repeatedly

Why use functions

Prevent code redundancy; do not use functions, poor code readability

How to use functions

  • Definition of function

    Keyword (DEF) function name (index) parentheses ():
    “” “function description: used to describe the function code body’s function” “”

    def index():
        "" "print a sentence
        :return:
        """
        Print ("this is a function")
  • The naming standard of function name is the same as that of variable

  • Types of functions

    • Parameter free function

      def index():
          "" "print a sentence
          :return:
          """
          Print ("this is a nonparametric function")
    • Empty function (only function name)

      def index():
          pass
    • Parametric function

      def login(username,password):
          print(username,password)
  • Function call

    • Direct call

      #Define register function 
      def register():
          "" "print name, age
          :return:
          """
          Print ("registered user: \ n Name: Dawn \ n age: 37 \ n")
      #Call register function directly
      register()
    • Define variable reception

      #Define register function
      def register():
          "" "print name, age
          :return:
          """
          Print ("registered user: \ n Name: Dawn \ n age: 37 \ n")
      #Define the variable res and assign the value of res to register
      per = register
      #Using res to call functions
      per()
    • Use functions as arguments

      #Define Max function
      def max(num1,nmu2):
          """
          Compare the size of two numbers and return the maximum number
          :param num1:
          :param nmu2:
          :return: max
          """
          #If num1 > num2, return num1, otherwise return num2, and assign the result to the max variable. Equivalent to if Else... Abbreviation
          max = num1 if num1 > nmu2 else nmu2
          return max
      #Using function nesting, max() is passed into max() again as a parameter
      print(max(187,max(89,233)))
  • Return value of function

    Return keyreturnExpress. Return isEnd of functionAs long as the function body code executes to return, the function execution ends

    The return value of the function is divided into five cases:

    • Do not write return: that is, there is no return value,Return to none by default

      def foo():
          "" "to demonstrate a function without return
          :return:
          """
          name = "dawn"
          age = 37
      
      Print (foo()) (print result: none)
    • Write only returnOnlyEnd effect of function body code, return to none

      def foo():
          """
          Use to demonstrate write return only
          :return: None
          """
          for i in range(2):
              while True:
                  i += 1
                  print(i)
                  if i == 1:
                      return
      
      Print (foo()) (print result: 1 and none 1 are the records printed out by the function
    • Return none: This is the same as writing only return none

      def foo():
          """
          Used to demonstrate return none
          :return: None
          """
          for i in range(3,0,-1):
              for j in range(i-1,-1,-1):
                  if j == 1:
                      return None
                  print(j)
      
      Print (foo()) (print result: 2 and none 2 are the records printed out by the function
    • Return single valueYes, yes.The returned result is treated as a variable or assigned to a variableUse

      def foo():
          """
          Use to show a value of return
          :return: min
          """
          min = 0
          num1 = 123.04
          num2 = 233.333
          min = num1 if num1 < num2 else num2
          return min
      
      Print (F "between 123.04 and 233.333, the smaller one is {foo()}")
    • Return multiple values: multiple values to be returned,Return in tuple (default)Can alsoSpecify the data type returned by yourself。 Stored in tuple, do not want the return value to be modified

      #Default return tuple
      def foo():
          """
          Used to show multiple values of return, multiple values are stored in tuples by default to return
          :return: (name,age,hobby,animals)
          """
          name = "dawn"
          age = 37
          hobby = ["study","read","music"]
          Animals = {"cat": "Sunday", "dog": "rice ball"}
          return name,age,hobby,animals
      
      Print (foo()) (print result tuple type record: ('dawn ', 37, ['Study', 'read', 'music'], {'cat': 'Sunday', 'dog': 'rice ball'})
      
      #Custom return value is Dictionary
      def foo1():
          """
          Used to show that multiple values can be returned in the form of a dictionary
          :return: {"name":name,"age":age,"hobby":hobby,"animals":animals}
          """
          name = "dawn"
          age = 37
          hobby = ["study", "read"]
          Animals = {"cat": "Sunday"}
          return {"name":name,"age":age,"hobby":hobby,"animals":animals}
      
      Print (foo1()) ාprint result dictionary type: {'name':'dawn ',' age ': 37,' hobby ': ['Study', 'read'],'animals': {'cat': 'Sunday'}}}}
  • Parameters of function

    fromtypeIn other words, the parameters are divided intoFormal parameterandReal reference

    Formal parameter: the parameters specified in the function definition phase. Equivalent to the variable name when the variable is defined

    Real reference: the parameter passed in during the function call phase. Equivalent to the variable value assigned to the variable

    #Username and password here are formal parameters
    def get_xspar(username,password):
        """
          Used to demonstrate formal and actual parameters
        : param Username: name
          : param and password: password
        :return:
          """
        Print (F "Name: {username} \ t password: {password}")
    
    #Here, "dawn" and "123" in the login function are arguments
    get_xspar("dawn","123")

    fromWay of referenceFor example, there are four types. Namely:Location parameter, keyword parameter, default parameter, variable length parameter

    • Position parameter: when a function is called, directly through theParameter list order parameter transferParameters

      def w_par(name,pwd):
              """
              Used to demonstrate location parameters
              : param Name: name
              : param PWD: password
              :return:
              """
              Print (F "user name: {name} \ tlogon password: {PWD}")
          W? Par ("dawn", "123")? Dawn "and" 123 "pass parameters in turn according to the parameter list, that is, the position parameter
    • Key parameters: when a function is called,Specify parameter name for parameter transferParameters

      def g_par(name,pwd,age):
          """
          For key parameters
          : param Name: name
          : param PWD: password
          : param age: age
          :return:
          """
          Print (F "Name: {name} \ tpassword: {PWD} \ theage: {age}")
      G ﹐ par (age = 18, name = "dawn", PWD = "123") ﹐ pass the value to the specified parameter, which is the keyword parameter

      Be careful:

      Location and key parametersIt can be mixed.Position parameter must beTo set thebeforeWhen mixed,Do not duplicate assignment to the same parameter

      def g_par(name,pwd,age):
          """
          Used to demonstrate a mix of location and key parameters
          : param Name: name
          : param PWD: password
          : param age: age
          :return:
          """
          Print (F "Name: {name} \ tpassword: {PWD} \ theage: {age}")
      
      G ﹐ par (name = "dawn", "123", age = 18) ﹐ error example, position parameter must be before keyword parameter
      G ﹣ par ("123", name = "dawn", age = 18) ᦇ error example: when the program is running, by default, "123", name = "dawn" is regarded as the value of parameter [name]
      G × par ("dawn", "123", age = 18) × correct example
    • Default parameters: in the define function phase, on theParameter assignment(that is to say)Parameter value set)Parameters for. When calling, if you do not pass values to this parameter, the system will automatically use the default value; if you pass values to this parameter,If the parameter is retransmitted, the default value will be modifiedDo not pass variable types as parameters

      Def fault_par (name, age, gender = "male"):
          """
          Used to demonstrate returning default value parameters
          : param Name: name
          : param age: age
          : param gender: gender, default value is [male]
          :return:
          """
          Print (F "Name: {name}, age: {age}, gender: {gender}")
      
      Default_par ("Egon", 73) ා no [gender] parameter is passed in, print result: Name: Egon, age: 73, gender: Male
      Fault ﹐ par ("dawn", 37, "female") ﹐ pass [gender] parameter, print result: Name: Dawn, age: 37, gender: Female
    • Variable length parameter: the number of parameter lists in a function may not be fixed

      *args: receives all overflow location parameters, and the received values are stored in a tuple.

      In fact,*argsIt is an official certification. The name after **** can be modified. As long as there is * in the * * parameter, it has the effect of variable length parameter * *.

      def args_par(name,age,*args):
          """
          Used to demonstrate the role of * args
          : param Name: name
          : param age: age
          : param args: overflow parameter
          :return:
          """
          Print (F "Name: {name}, age: {age}. Overflow parameter: {args} ")
      
      Args ﹐ par ("Egon", 73) ﹐ normal input parameters, printing result: Name: Egon, age: 73. Overflow parameters: ()
      Args? Par ("Sean", 18, "male", "perm")? Two more parameters are passed. The print result is: Name: Sean, age: 18. Overflow parameter: ('male', 'scald')

      It should be noted that:

      *****In parameter, it means receiving overflow parameter, in parameter, it means scattering data of container type.#The function has several parameters, and the length of the arguments is a few bits. Otherwise, an error is reported. The dictionary passed in the key value

      def s_par(name,age,str):
          """
          Used to demonstrate that in an argument, * means intended
          : param STR: passed in container type data, STR, list, tuple, dict, set
          :return:
          """
          print(name,age,str)
      
      S? Par (* "s e a")? Print result: s e a
      S ﹐ par (* ['sean ',' 18 ',' male ']) ﹐ print result: Sean 18 male
      S ﹣ (* ('a ', 1,' C ') print result: a 1 c
      S ා par (* {"name": "Sean", "age": 18, "gender": "male"}) ා the dictionary passed in the key print result: name age gender
      S {1 ',' a ', 233}) print result: a 233 1

      **Kwargs: receives all overflowed keyword parameters,The received values are stored in a dictionary。 When outputting, use kwargs directly; if it is*Kwargs, indicating that all key values in the dictionary are to be output

      def kwargs_par(name,age,**kwargs):
          """
          Used to demonstrate the function of * * kwargs
          : param Name: name
          : param age: age
          : param kwargs: overflow keyword parameter dictionary
          :return:
          """
          Print (F "Name: {name}, age: {age}, overflow location parameter Dictionary: {kwargs}")
          Print (F "overflow location parameter after break:", end = "")
          print(*kwargs)
      
      kwargs_par(age=18,gender="male",hobby="['study','read']",name="sean")
      #Print results:
      #Name: Sean, age: 18, overflow location parameter Dictionary: {'gender': 'male', 'hobby': "['Study ',' read ']}"
      #Overflow location parameter after break up: gender hubby