Python UDF tutorial, python UDF

Source: Internet
Author: User

Python UDF tutorial, python UDF

In Python, define a function to use the def statement, write the function name, parameters in brackets, and colons in sequence, and then write the function body in the indent block, the return Value of the function is returned using the return statement.

Let's take a custom my_abs function for absolute value as an example:

def my_abs(x):  if x >= 0:    return x  else:    return -x

Test and call my_abs to check whether the returned results are correct.

Note that when executing a statement in the function body, once return is executed, the function is executed and the result is returned. Therefore, functions can implement complex logic through conditional judgment and loops.

If there is no return statement, the result is returned after the function is executed, but the result is None.

Return None can be abbreviated as return.
Empty Function

If you want to define an empty function that does nothing, you can use the pass statement:

def nop():  pass

The pass statement does not do anything. What is the purpose? In fact, pass can be used as a placeholder. For example, if you haven't thought about how to write the function code yet, you can put a pass first so that the code can run.

Pass can also be used in other statements, such:

if age >= 18:  pass

If pass is missing, a syntax error occurs when the code runs.
Parameter check

When a function is called, if the number of parameters is incorrect, the Python interpreter automatically checks the number and throws a TypeError:

>>> my_abs(1, 2)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: my_abs() takes exactly 1 argument (2 given)

However, if the parameter type is incorrect, the Python interpreter cannot help us check the parameter type. Try the difference between my_abs and the built-in function abs:

>>> my_abs('A')'A'>>> abs('A')Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: bad operand type for abs(): 'str'

When an inappropriate parameter is input, the built-in function abs will check the parameter error, and the defined my_abs does not have a parameter check. Therefore, this function is not well defined.

Let's modify the definition of my_abs and check the parameter type. Only parameters of integer and floating-point types are allowed. You can use the built-in function isinstance to check data types:

def my_abs(x):  if not isinstance(x, (int, float)):    raise TypeError('bad operand type')  if x >= 0:    return x  else:    return -x

After a parameter check is added, if the input parameter type is incorrect, the function can throw an error:

>>> my_abs('A')Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in my_absTypeError: bad operand type

Error and exception handling will be discussed later.
Returns multiple values.

Can a function return multiple values? The answer is yes.

For example, in the game, you often need to move from one point to another, and give coordinates, displacement, and angle to calculate new coordinates:

import mathdef move(x, y, step, angle=0):  nx = x + step * math.cos(angle)  ny = y - step * math.sin(angle)  return nx, ny

In this way, we can get the return value at the same time:

>>> x, y = move(100, 100, 60, math.pi / 6)>>> print x, y151.961524227 70.0

But in fact this is just an illusion that the Python function returns a single value:

>>> r = move(100, 100, 60, math.pi / 6)>>> print r(151.96152422706632, 70.0)

The original return value is a tuple! However, in syntax, a tuple can be returned without parentheses, while multiple variables can receive a tuple at the same time and assign the corresponding value by position, A Python function returns a tuple, but it is easier to write.
Summary

When defining a function, you must determine the function name and number of parameters;

If necessary, check the data type of the parameter;

The function body can use return to return function results at any time;

If no return statement is returned after the function is executed, the return None statement is automatically returned.

A function can return multiple values at the same time, but it is actually a tuple.

 

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.