程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python functions

編輯:Python

function


Functions are organized , Reusable , To achieve oneness , Or code snippets associated with functions .

Function can improve the modularity of application , And code reuse . You already know Python Many built-in functions are provided , such as print(). But you can also create your own functions , This is called a user-defined function .


Define a function

You can define a function that you want to function , Here are the simple rules :

  • Function code block to def Key words start with , Followed by function identifier name and parentheses ().
  • Any arguments and arguments passed in must be placed between parentheses . Parentheses can be used to define parameters .
  • The first line of the function optionally uses the document string — Used to store function descriptions .
  • Function contents start with a colon , And indent .
  • return [ expression ] End function , Optionally return a value to the caller . Without expression return It's equivalent to returning to None.

  • grammar

    deffunctionname(parameters): " function _ docstring "function_suitereturn[expression]

    By default , Parameter values and parameter names match in the order defined in the function declaration .

    example

    Here is a simple Python function , It takes a string as an incoming parameter , Then print it to the standard display device .

    example (Python 2.0+)

    defprintme(str): " Print the incoming string to the standard display device "printstrreturn

    Function call

    Defining a function only gives the function a name , Specifies the parameters contained in the function , And code block structure .

    After the basic structure of this function is completed , You can do this through another function call , You can also go straight from Python Prompt execution .

    The following example calls printme() function :

    example (Python 2.0+)

    #!/usr/bin/python# -*- coding: UTF-8 -*-

    # Defined function
    defprintme(str):
    “ Print any incoming strings ”
    printstr
    return

    # Call function
    printme(“ I'm going to call user defined functions !”)
    printme(“ Call the same function again ”)

    The output of the above example :

     I'm going to call user defined functions !
     Call the same function again 

    Parameter passing

    stay python in , Type belongs to object , Variables have no type :

    a=[1,2,3]

    a=“Runoob”

    In the above code ,[1,2,3] yes List type ,"Runoob" yes String type , Variables a There is no type , She's just a reference to an object ( A pointer ), It can be List Type object , You can also point to String Type object .

    Changeable (mutable) And cannot be changed (immutable) object

    stay python in ,strings, tuples, and numbers Is an object that cannot be changed , and list,dict And so on are modifiable objects .

    • Immutable type : Variable assignment a=5 After the assignment a=10, This is actually a new generation of int The value object 10, let a Pointing to it , and 5 To be discarded , Not change a Value , It's equivalent to a new generation of a.

    • Variable type : Variable assignment la=[1,2,3,4] After the assignment la[2]=5 Will be list la The third element value of changes , In itself la Didn't move , Only part of its internal value has been modified .

    python Parameter passing of function :

    • Immutable type : similar c++ Value transfer of , Such as Integers 、 character string 、 Tuples . Such as fun(a), It's just a Value , No impact a Object itself . For example fun(a) Internal modification a Value , Just modify another copied object , Does not affect the a In itself .

    • Variable type : similar c++ By reference , Such as list , Dictionaries . Such as fun(la), Will be la Really pass it on , After modification fun External la It will also be affected

    python Everything in is the object , Strictly speaking, we can't say value passing or reference passing , We should talk about immutable objects and mutable objects .

    python Pass immutable object instance

    example (Python 2.0+)

    #!/usr/bin/python# -*- coding: UTF-8 -*-

    defChangeInt(a):
    a = 10

    b = 2
    ChangeInt(b)
    printb# The result is 2

    In the case of int object 2, The variable that points to it is b, Pass on to ChangeInt Function time , The variables are copied as values b,a and b All point to the same Int object , stay a=10 when , Then a new int The value object 10, And let a Pointing to it .

    Pass variable object instance

    example (Python 2.0+)

    #!/usr/bin/python# -*- coding: UTF-8 -*-

    # Write function description
    defchangeme(mylist):
    “ Modify the incoming list ”
    mylist.append([1,2,3,4])
    print" Value in function : ", mylist
    return

    # call changeme function
    mylist = [10,20,30]
    changeme(mylist)
    print" Value outside the function : ", mylist

    The object passing in the function and adding new content at the end of the instance use the same reference , So the output is as follows :

     Value in function : [10, 20, 30, [1, 2, 3, 4]]
     Value outside the function : [10, 20, 30, [1, 2, 3, 4]]

    Parameters

    Here are the formal parameter types that can be used when calling a function :

    • Required parameters
  • Key parameters
  • Default parameters
  • Indefinite length parameter
  • Required parameters

    The necessary parameters must be passed in the correct order into the function . The number of calls must be the same as when they were declared .

    call printme() function , You have to pass in a parameter , Otherwise, there will be grammatical errors :

    example (Python 2.0+)

    #!/usr/bin/python# -*- coding: UTF-8 -*-

    # Write function description
    defprintme(str):
    “ Print any incoming strings ”
    printstr
    return

    # call printme function
    printme()

    The output of the above example :

    Traceback (most recent call last):
    File "test.py", line 11, in <module>
    printme()
    TypeError: printme() takes exactly 1 argument (0 given)

    Key parameters

    Keyword parameters are closely related to function calls , Function calls use key arguments to determine the value of the arguments passed in .

    Using keyword parameters allows the order of parameters when a function is called to be different from when it is declared , because Python The interpreter can match parameter values with parameter names .

    The following example is in the function printme() Call with parameter name :

    example (Python 2.0+)

    #!/usr/bin/python# -*- coding: UTF-8 -*-

    # Write function description
    defprintme(str):
    “ Print any incoming strings ”
    printstr
    return

    # call printme function
    printme(str = “My string”)

    The output of the above example :

    My string

    The following example can show more clearly that the order of key parameters is not important :

    example (Python 2.0+)

    #!/usr/bin/python# -*- coding: UTF-8 -*-

    # Write function description
    defprintinfo(name, age):
    “ Print any incoming strings ”
    print"Name: ", name
    print"Age ", age
    return

    # call printinfo function
    printinfo(age=50, name=“miki”)

    The output of the above example :

    Name: miki
    Age 50

    Default parameters

    When you call a function , If the value of the default parameter is not passed in , Is considered the default value . The following example will print the default age, If age Not passed in :

    example (Python 2.0+)

    #!/usr/bin/python# -*- coding: UTF-8 -*-

    # Write function description
    defprintinfo(name, age = 35):
    “ Print any incoming strings ”
    print"Name: ", name
    print"Age ", age
    return

    # call printinfo function
    printinfo(age=50, name=“miki”)
    printinfo(name=“miki”)

    The output of the above example :

    Name: miki
    Age 50
    Name: miki
    Age 35

    Indefinite length parameter

    You may need a function that can handle more arguments than it was originally declared . These parameters are called indefinite length parameters , And above 2 The parameters are different , Declaration will not be named . The basic grammar is as follows :

    deffunctionname([formal_args,] *var_args_tuple): " function _ docstring "function_suitereturn[expression]

    With an asterisk (*) The variable name of will hold all unnamed variable parameters . Examples of indefinite length parameters are as follows :

    example (Python 2.0+)

    #!/usr/bin/python# -*- coding: UTF-8 -*-

    # Write function description
    defprintinfo(arg1, *vartuple):
    “ Print any incoming parameters ”
    print" Output : "
    printarg1
    forvarinvartuple:
    printvar
    return

    # call printinfo function
    printinfo(10)
    printinfo(70, 60, 50)

    The output of the above example :

     Output :
    10
     Output :
    70
    60
    50

    Anonymous functions

    python Use lambda To create anonymous functions .

    • lambda It's just an expression , Function volume ratio def Simple a lot .
    • lambda The subject of is an expression , Not a block of code . Only in lambda Expressions encapsulate limited logic .
    • lambda Function has its own namespace , And can't access parameters outside of its own parameter list or in the global namespace .
    • although lambda The function looks like it can only write one line , But it's not the same as C or C++ Inline function , The purpose of the latter is not to occupy stack memory when calling small functions so as to increase the running efficiency .
    • grammar

      lambda The syntax of a function contains only one statement , as follows :

      lambda [arg1 [,arg2,.....argn]]:expression

      The following example :

      example (Python 2.0+)

      #!/usr/bin/python# -*- coding: UTF-8 -*-

      # Write function description
      sum = lambdaarg1, arg2: arg1 + arg2

      # call sum function
      print" The sum is : ", sum(10, 20)
      print" The sum is : ", sum(20, 20)

      The output of the above example :

       The sum is  : 30
       The sum is  : 40

      return sentence

      return sentence [ expression ] Exit function , Optionally return an expression... To the caller . Without parameter value return Statement returns None. None of the previous examples demonstrated how to return a value , The next example tells you how to do :

      example (Python 2.0+)

      #!/usr/bin/python# -*- coding: UTF-8 -*-

      # Write function description
      defsum(arg1, arg2):
      # return 2 The sum of parameters ."
      total = arg1 + arg2
      print" Within the function : ", total
      returntotal

      # call sum function
      total = sum(10, 20)

      The output of the above example :

       Within the function  : 30

      Variable scope

      Not all variables of a program can be accessed in any location . Access depends on where the variable is assigned .

      The scope of the variable determines which specific variable name you can access in which part of the program . The two most basic variable scopes are as follows :

      • Global variables
    • local variable

    • Global and local variables

      Variables defined within a function have a local scope , Define a global scope outside the function .

      Local variables can only be accessed inside the function they are declared , Global variables can be accessed throughout the program . When you call a function , All variable names declared within the function will be added to the scope . The following example :

      example (Python 2.0+)

      #!/usr/bin/python# -*- coding: UTF-8 -*-

      total = 0# This is a global variable
      # Write function description
      defsum(arg1, arg2):
      # return 2 The sum of parameters ."
      total = arg1 + arg2# total Here is the local variable .
      print" Function is a local variable : ", total
      returntotal

      # call sum function
      sum(10, 20)
      print" Outside the function is the global variable : ", total

      The output of the above example :

       Function is a local variable  : 30
       Outside the function is the global variable  : 0

    1. 上一篇文章:
    2. 下一篇文章:
    Copyright © 程式師世界 All Rights Reserved