6. define functions, function parameters, and parameters.

Source: Internet
Author: User

6. define functions, function parameters, and parameters.

Content:

  • Function Definition Method
  • Function text description
  • Null operation statement
  • Location parameters
  • Default parameters
  • Key parameters
  • Variable Length Parameter
Function definition method:

 

 

Function text description:

To help others understand the meaning of a function or avoid forgetting it, you can use a string (no value assignment, single quotation marks, double quotation marks, and multiple quotation marks are required) and # comment the text description at the beginning of the function.

Def function1 (): "This is the description of this program" print ("hello function") return 1function1 ()

 

Empty operation statement:

The pass statement is an empty operation statement. If pass is used, no operation is performed:

 

An empty function does not execute any operation. It is defined using the pass statement.

def pass_function():    pass

Pass can also be used in loop statements:

if a>0:    pass

 

Function parameters:

 

All parameters (parameters) in Python are passed through references. If you change the content referred to by the reference class parameter in a function, the change is also reflected outside the called function.

>>> a=[1,2,3,4,5,6]>>> def change(x):    x.append("changed")    >>> change(a)>>> a[1, 2, 3, 4, 5, 6, 'changed']

Def test2 (x): print (id (x) test2 (x) print (id (x) # point

However, when the data pointing to a parameter is modified in the function, the externally passed parameters are not modified, because in this case, the function generates a local variable to avoid modifying the external variable by mistake:

If you want to modify the external variables, you must declare the variables using global before making the changes.

Print ("------ volume changed globally --------") print ("before:", x) def test_globol (): global x = 6test_globol () print ("after_test_globol :", x)

How to check function input parameter types:

1. When an inappropriate parameter is passed in, built-in functions usually check for parameter errors and prompt TypeError or ValueError. For example

>>> int("abc")Traceback (most recent call last):  File "<pyshell#37>", line 1, in <module>    int("abc")ValueError: invalid literal for int() with base 10: 'abc'>>> int ('10')10
>>> int('10','12')Traceback (most recent call last):  File "<pyshell#46>", line 1, in <module>    int('10','12')TypeError: 'str' object cannot be interpreted as an integer

This is because built-in functions generally perform parameter checks.

Sometimes we need to consider parameter checks when defining functions to improve our functions.

Check the parameter type. You can use built-in functions to check the data type.isinstance()To achieve this, raise can throw an exception:

"If not isinstance (parameter, (type 1 allowed by the parameter, type 2 allowed ...)) raise TypeError ('custom parameter error prompting ') "def my_int (x): if not isinstance (x, int): raise TypeError (" You entered not an integer ") print (x)

 

Location parameters:
  • Values are assigned according to the location.
def num002(a,b):    print(a,b)keynum002("haha","helloworld")#a->"haha",b->"helloworld"

 

Default parameters:

1. default parameters can simplify the input of parameters.

For example, some commonly used values do not need to be passed in. One example is student information input. Most students of the same grade are of the same age, so the input of age parameters can be simplified.

  • If the variable name is not specified, default parameters are provided by location.
  • When some default parameters are not provided in order, you need to write the parameter name, and the variable with the given parameter name cannot be a variable without the given parameter name.
  • If a parameter does not have a default value, the "required" parameter must be defined before the default parameter.

# If a parameter does not have a default value, def student2 (name = "aotuman", sex, age = 18) must be defined before the default parameter ): print (name, sex, age) student ("lili", "m ")

Because the default parameters generate objects in advance, you can directly use the default parameters for variable objects, which may cause multiple function operations to use the same variable:

Print ("memory problems with default parameters ". center (50, "-") def student3 (name, sex, age = 18): print (name, sex, age, id (age) student3 ("lili ", "m") student3 ("lilei", "f") # The result is displayed with the default parameter, id (age) the memory points to the same # So pay attention to use the variables pointing to the class (list .....)

 

Student3 ("hanmeimei", "m", 17) def my_append (x, list1 = []): list1.append (x) print (list1) my_append ("haha ") my_append ("hehe") # The result shows that the data of the last result is left in the default parameter.

 

To solve the problem above, you can move the default parameter assignment step to the Execution Code:

 

Print ("Improvement Result ". center (50, "-") def my_append2 (x, list1 = None): if list1 is None: list1 = [] list1.append (x) print (list1)


 

 

Key parameters:
  • Key Parameter. When a parameter is input, the parameter name is explicitly specified to specify the Parameter
  • However, key parameters cannot be written before the location parameter.
# Key parameters: explicitly specify the print ("\ n ----- key parameter -------") def keynum002 (a, B): print (a, B) keynum002 (B = "haha", a = "helloworld") "keynum002 (B =" haha "," helloworld ") # No, the key parameter cannot be the "" Before the Location Parameter """

 

 

 

Variable Length parameters:
  • The variable length parameter indicates that the number of input parameters is variable.
  • If you want to input multiple parameters, you can store the parameters in the list, tuple, and dict variables, and then pass the variables to the function:
>>> def can_change(l):    print("%s %s" % (l[0],l[1]))    >>> l1=["apple","pen"]>>> can_change(l1)apple pen

 

  • Python defines the Parameter definition method of variable parameters. Adding * Before a parameter indicates that it is a tuples, and adding ** indicates that it is a dictionary. When passing values, the corresponding tuples or dictionaries are imported.

In this way, variable parameters have default values, which are empty tuples or empty dictionaries by default.

If both * And ** are used, the "*" tuples must be before the "**" dictionary parameter.

When passing in a parameter, you can add the corresponding variable parameter "*" or "**" to avoid the problem that the input parameter location does not correspond to the function parameter location in some cases.

Def change34 (value1, * value2, ** value3): print (value1, end = '\ t') print (value2, end =' \ t') print (value3, end = '\ t') change34 () # *** the default value is print ("\ n") change34 )) #1 overflow to the previous value1print ("\ n") change34 (* (1, 2,} overflow to the previous value2print ("\ n") change34 ("value1", * (), ** {'1': 1, '2': 2 }) print ("\ n") print ("test2 ". center (50 ,'-'))

 

 

  • You can use multiple keyword parameters to enter a dictionary parameter.
Def test2 (** args): # ** you can accept key parameters. * You can only accept the location parameter print (args) test2 (x = 1, y = 2, c = 3) test2 (** {'X': 1, 'y': 2, 'C': 3 })

 

Related Article

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.