Introduction
In Python there is also the concept of functions, the standard function we can call built-in functions, such functions can be directly called through the function name. But there are other functions that are not built-in that cannot be called directly from the function name, such as the floor function (rounding down), and we need to use the module; This article mainly introduces math and Cmath.
Python version: 3.4.4
Built-in functions (standard functions)
Let's take a look at the standard function, and if you test with the idle program, the color of the function name will turn purple when you enter the built-in function, not the built-in function.
1.abs: Absolute Value
>>> ABS (-5)5
2.pow (x, y): x y-square
>>> Pow (2,3)8
Non-built-in functions
Grammar
Import Math[cmath]math[cmath].function_name
Or
From Math[cmath] Improt function_name
Note: The usage of Cmath is the same as math, but Cmath is used to deal with complex numbers, such as when you need to square root a negative number, you need to use Cmath
1.floor: Rounding Down
>>> Floor (31.5) Traceback (recent): "<pyshell#70> "1 in <module> floor (31.5' ) Floor ' is not defined
Because floor is not a standard function, the direct call will error, then need to use the module.
>>> Import Math>>> Math.floor (31.5)
from Math Importfloor >>> floor (31.5)
2.sqrt: Take square root
>>> Import Math>>> math.sqrt (4)2.0>>> math.sqrt (- 4 ) Traceback (most recent) :"<pyshell#82>"1 in <module> math.sqrt (-4) Valueerror:math domain error
You can see that using math to take the square root of negative numbers will be an error, then you need to use Cmath
>>> Import Cmath>>> cmath.sqrt (-4) 2j
from cmath import sqrt>>> sqrt (-4) 2j
Other functions
Summary
The syntax of Python changes in every new version and requires constant attention to where each new version has changed.
Note: pursuer.chen Blog:http://www.cnblogs.com/chenmh This site all the essays are original, welcome to reprint, but reprint must indicate the source of the article, and at the beginning of the article clearly give the link. Welcome to the exchange of discussions |
Python Functions and modules