Python functions,
Evaluate the absolute value function abs () function max () can receive any number of parameters and return the largest >>> max (1, 2) 2 >>> max (2, the 3, 1,-5) 3int () function can convert other data types to Integers >>> int ('000000') 123 >>> int (123) 12 >>> float ('12. 34 ') 12.34 >>> str (1.23) '1. 23' >>> str (100) '20140901' >>> bool (1) True >>> bool ('') False
The function name is actually a reference to a function object. You can assign the function name to a variable, which is equivalent to an alias for the function ":
>>> A = abs # variable a points to abs function >>> a (-1) # so you can call abs function 1 through.
Define functions
In Python, define a function to usedefStatement, write the function name, parameters in parentheses, and colons in sequence:Then, write the function body in the indent block. The return value of the function isreturnStatement.
If you havemy_abs() The function definition is savedabstest.py The Python interpreter can be started in the current directory of the file.from abstest import my_abs To importmy_abs() Function, noteabstestYes file name (not including.pyExtension ):
If you want to define an empty function that does nothing, you can usepassStatement:
def nop(): pass
passIt can be used as a placeholder. For example, you can putpassTo run the code.
Can a function return multiple values? The answer is yes.
import mathdef move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny
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 returned 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.
Parameter location parameter of the Function
def power(x, n): s = 1 while n > 0: n = n - 1 s = s * x return s
power(x, n)The function has two parameters:xAndn, Both parameters areLocation parametersWhen the function is called, the two values passed in are assigned to the parameter in order of position.xAndn.
Default parameters
def power(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s
The default value of the second parameter n is set to 2. In this way, when we callpower(5) Is equivalent to callingpower(5, 2)。