Python's Calling function
Python has built in a lot of useful functions that we can call directly.
To invoke a function, you need to know the name and parameters of the function, such as a function that asks for an absolute value abs
, and only one argument. Documents can be viewed directly from the official Python website:
Http://docs.python.org/3/library/functions.html#abs
You can also help(abs)
view the abs
function's help information on the interactive command line.
Call abs
function:
>>> ABS (100>>>) abs ( -20)20>>> abs (12.34)12.34
When calling a function, if the number of arguments passed in is incorrect, the error will be reported TypeError
, and Python will tell you explicitly that abs()
there are only 1 parameters, but two are given:
>>> ABS (1, 2) Traceback (most recent ):"<stdin>" in <module>typeerror:abs () takes exactly one argument (2 given)
If the number of arguments passed in is correct, but the parameter type cannot be accepted by the function, TypeError
the error is reported, and an error message str
is given: is the wrong parameter type:
>>> ABS ('a') Traceback (most recent call last): "< stdin>" in <module>for'str'
Instead max
, the function max()
can receive any number of arguments and return the largest one:
>>> Max (1, 2)2>>> Max (2, 3, 1,-5)3
Data type conversions:
Python's built-in common functions also include data type conversion functions, such as int()
functions that convert other data types to integers:
>>> int ('123')123>>> int (12.34)12>>> Float ('12.34')12.34>>> str (1.23)'1.23 '>>> str ' [+]>>> bool (1 ) True>>> bool (") False
The function name is actually a reference to a function object, and it is possible to assign a function name to a variable, which is equivalent to giving the function an "alias":
# variable a points to the ABS function # so you can also call the ABS function by a 1
Practice
Use the Python built-in hex()
function to convert an integer to a hexadecimal-represented string:
# -*-coding:utf-8-*- = 255= Print(Hex (N1))print(Hex (n2))
#!/usr/bin/env Python3#-*-coding:utf-8-*-x= ABS (100) y= ABS (-20)Print(x, y)Print('Max (1, 2, 3) =', Max (1, 2, 3))Print('min (1, 2, 3) =', min (1, 2, 3))Print('sum ([1, 2, 3]) =', sum ([1, 2, 3]))
Python's Calling function