Python-function usage, python-Function

Source: Internet
Author: User

Python-function usage, python-Function
Introduction

Functions in Python provide organized and reusable code to execute a group of operations. The function simplifies the coding process, prevents redundant logic, and makes the code easier to follow.

 

Define and call simple functions

UsedefStatement to define the most common method of functions in Python. The syntax of this statement is as follows:

def function_name(parameters):    statement(s)

Function_name is calledIdentifier. Since the function definition is an executable statement, its executionBindThe identifier that can be used later is called a function object.

Parameters is an optional identifier list that is bound to the value provided as a parameter when a function is called. A function can have any number of parameters separated by commas.

statement(s)-Also knownFunction body-It is a non-empty sequence of statements executed when each function is called. This means that a function body cannot be empty.

Here is a simple function definition to print an exampleHelloEach time is called time:

def greet():    print("Hello")

Now, let's definegreet()Function:

greet()# Out: Hello

This is another example of a function definition. It accepts a parameter and displays the input value each time a function is called:

def greet_two(greeting):    print(greeting)

After that,greet_two()The function must be called with parameters:

greet_two("Howdy")# Out: Howdy

You can also give this function parameter a default value:

def greet_two(greeting="Howdy"):    print(greeting)

Now you can call this function without providing a value:

greet_two()# Out: Howdy

You will notice that, unlike many other languages, you do not need to explicitly declare the function return type. Python functions can return any type of ValuereturnKeyword. A function can return any number of different types!

def many_types(x):    if x < 0:        return "Hello!"    else:        return 0print many_types(1)print many_types(-1)# Output:0Hello!

This is a fully valid Python code as long as the caller processes it correctly.

When the execution ends, functions without return statements always returnNone:

def do_nothing():    passprint(do_nothing())# Out: None

As mentioned above, the function definition must have a function body, a sequence of non-null statements. Therefore,passThe statement is used as the function body. This is an empty operation. When it is executed, nothing will happen. When a statement is required, it is useful as a placeholder, but does not need to execute code.

 

Define a function with any number of parameters

Any number of location parameters:

 

You can add a parameter before the parameter to define a function that can obtain any number of parameters.*

def func(*args):    # args will be a tuple containing all values that are passed in    for i in args:        print(i)func(1, 2, 3)  # Calling it with 3 arguments# Out: 1#      2#      3list_of_arg_values = [1, 2, 3]func(*list_of_arg_values)  # Calling it with list of values, * expands the list# Out: 1#      2#      3 func()  # Calling it without arguments# No Output 

YouNoProvides a defaultargsFor examplefunc(*args=[1, 2, 3])Will cause a syntax error (or even not compile ).

YouNoWhen calling a function, for example, providing thesefunc(*args=[1, 2, 3])Will increaseTypeError.

However, if you already have your arguments in the array (or otherIterable), YouYesYou can call the following functions:func(*my_stuff).

These parameters (*args) Can be accessed through indexes, suchargs[0]The first parameter is returned.

Any number of keyword Parameters

You can get a name parameter by defining any number of parameters defined in2 *In front of it:

def func(**kwargs):    # kwargs will be a dictionary containing the names as keys and the values as values    for name, value in kwargs.items():        print(name, value)func(value1=1, value2=2, value3=3)   # Calling it with 3 arguments# Out: value2 2#      value1 1#      value3 3func()                               # Calling it without arguments# No Out putmy_dict = {'foo': 1, 'bar': 2}func(**my_dict)                      # Calling it with a dictionary# Out: foo 1#      bar 2

 

YouNoProvide theseNoName, suchfunc(1, 2, 3)Will triggerTypeError.

kwargsIs a common local python dictionary. For example,args['value1']Parameter Valuevalue1. Be sure to confirm whether there is such a statement orKeyErrorWill be improved.

Warning

You can mix these with other optional and required parameters, but the order within the definition is important.

TheLocation/keywordThe parameter is placed first. (Required parameter ).
ThenArbitrary *argParameters. (Optional ).
SoOnly keywordArgument. (Required ).
Finally,Any keyword **kwargsYes. (Optional ).

#       |-positional-|-optional-|---keyword-only--|-optional-|def func(arg1, arg2=10 , *args, kwarg1, kwarg2=2, **kwargs):     pass

 

  • arg1Must be given; otherwise,TypeErrorIncrease. It can be given as a location (func(10)) Or keyword parameter (func(arg1=10)).
  • kwarg1But it can only be provided as a keyword parameter:func(kwarg1=10).
  • arg2Andkwarg2Is optional. If this value is the same as the rule to be changedarg1(Whether it is a location or a keyword) andkwarg1(Only for keywords) applicable.
  • *argsCapture additional location parameters. But note that,arg1Andarg2Must be provided as a location parameter*args:func(1, 1, 1, 1).
  • **kwargsCapture all other keyword parameters. In this case, there is no Parameterarg1,arg2,kwarg1Orkwarg2. For example:func(kwarg3=10).
  • In Python 3, you can use*It indicates that all subsequent parameters must be specified as keywords. For examplemath.iscloseFeatures and higher usage requirements in Python 3.5def math.isclose (a, b, *, rel_tol=1e-09, abs_tol=0.0)This means that the first two parameters can be provided at the location, but the third and fourth parameters can only be provided as the keyword parameter.

 

Python 2.x does not support keyword-only parameters. This behavior can be followed.kwargs:

def func(arg1, arg2=10, **kwargs):    try:        kwarg1 = kwargs.pop("kwarg1")    except KeyError:        raise TypeError("missing required keyword-only argument: 'kwarg1'")    kwarg2 = kwargs.pop("kwarg2", 2)    # function body ...

 

Considerations for naming

Naming Conventions for optional location parametersargsAnd optional keyword ParameterskwargsJust an agreementYesUse any name you like,It is useful to follow the Convention to let others know what you are doing,Or even laterSo please do not.

Note uniqueness

Any function can be definedNo or one *argsAndNone or **kwargs, But not with each or more. Also*args RequiredIs the last location parameter, and**kwargsIt must be the last parameter. Try to use more than oneSetCauses a syntax error.

Precautions for nested functions with optional parameters

This function can be nested, and the General Convention is to delete projects that have been processed by code.,If you are inheriting parameters, you need to pass an optional location ARGS*The prefix and the optional keyword ARGS.**Prefix. Otherwise, ARGS can be passed as a list or tuples, and kwargs can be passed as a single dictionary. For example:

def fn(**kwargs):    print (kwargs)    f1(**kwargs)def f1(**kwargs):    print(len(kwargs))fn(a=1, b=2)# Out:# {'a': 1, 'b': 2}# 2

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.