On Python function definition

ysds20211402 2022-05-14 14:24:43 阅读数:159

pythonfunctiondefinition

from : Micro reading   https://www.weidianyuedu.com

stay Python in , Define a function to use def sentence , Write the function names in turn 、 Brackets 、 Parameters and colons in brackets :, then , Write function bodies in indented blocks , The return value of the function is return Statement returns .

Let's customize an absolute value my_abs Function as an example :

def my_abs(x):

    if x >= 0:

        return x

    else:

        return -x

Please test and call my_abs See if the returned result is correct .

Please note that , The statement inside the function body is executed , Once implemented to return when , The function is finished , And return the result . therefore , Function can realize very complex logic through condition judgment and loop .

without return sentence , The result will be returned after the function is executed , It just turned out to be None.

return None I could just write it as return.

Empty function

If you want to define an empty function that does nothing , It can be used pass sentence :

def nop():

    pass

pass Sentences do nothing , What's the use of that ? actually pass Can be used as a placeholder , For example, I haven't figured out how to write function code yet , You can put one first pass, Let the code run .

pass It can also be used in other sentences , such as :

if age >= 18:

    pass

Lack of pass, Code runs with syntax errors .

Parameter check

When you call a function , If the number of parameters is wrong ,Python The interpreter will automatically check out , And throw 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)

But if the parameter type is wrong ,Python The interpreter can't help us check . try my_abs And built-in functions abs The difference between :

>>> 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 passed in , Built in functions abs The parameter error will be checked , And what we define my_abs No parameter check , therefore , This function definition is not perfect .

Let's revise my_abs The definition of , Check the parameter type , Only integer and floating-point type parameters are allowed . Data type checking can be done with built-in functions isinstance Realization :

def my_abs(x):

    if not isinstance(x, (int, float)):

        raise TypeError("bad operand type")

    if x >= 0:

        return x

    else:

        return -x

After adding parameter check , If the wrong parameter type is passed in , 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_abs

TypeError: bad operand type

Error and exception handling will be discussed later .

Return multiple values

Can functions return multiple values ? The answer is yes .

For example, in the game, you often need to move from one point to another , Give the coordinates 、 Displacement and angle , You can calculate new coordinates :

import math

def move(x, y, step, angle=0):

    nx = x + step * math.cos(angle)

    ny = y - step * math.sin(angle)

    return nx, ny

So we can get the return value at the same time :

>>> x, y = move(100, 100, 60, math.pi / 6)

>>> print x, y

151.961524227 70.0

But in fact, it's just an illusion ,Python The function still 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 grammar , Return to one tuple Brackets can be omitted , Multiple variables can receive one at the same time tuple, Assign corresponding value by position , therefore ,Python The function of returns multiple values is actually to return a tuple, But it's easier to write .

Summary

When defining a function , You need to determine the function name and the number of arguments ;

If necessary , You can check the data type of the parameter first ;

Function body can be used inside return Return function results at any time ;

The function is not finished return When the sentence is , Automatically return None.

Functions can return multiple values at the same time , But it's actually a tuple.

版权声明:本文为[ysds20211402]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/134/202205141419107990.html