Python: Bult-in Functions for Numeric types
Python has some built-in functions for working with numeric types. Some of them are described below: ———–
|
Function Name |
Descriptions |
Code Example |
|
abs |
The abs(x) function takes the absolute value of any integer, long integer or floating point number.
When applied to a complex number, the function returns the magnitude of the number, which is distance from that point to the origin in the complex plane. |
>>> abs(-5.0) 5.0 >>> abs(-2) 2 >>> abs(5+2j) 5.3851648071345037 |
|
coerce |
The coerce(x,y) function applies numeric conversion rules(described below the table) to two numbers and return them as tuple. |
>>coerce(5,2.5) (5.0,2.5) >>coerce(5.5,5+2j) (5.5+0j,5+2j) |
|
divmod |
The functions divmod(a,b) performs long division on two numbers and returns the quotient and remainder. |
>>> divmod(5,2) (2, 1) >>> divmod(5.5,2.5) (2.0, 0.5) |
|
pow |
The functions pow(x,y[,z]) performs power operation.
As usual, Python coerces the two numbers to a common type if needed. If the resulting type can’t express the correct result then python will show an error message. An optional third argument to pow specifies the modulo operation to perform on the result. |
>>> pow(2,3) 8 >>> pow(2,-1) 0.5 >>> pow(2,5,10) 2 |
For all the built-in functions and there definitions, please visit this link:
http://docs.python.org/library/functions.html
Numeric Conversion Rule:
- If one of the numbers is a complex number then convert the other two a complex number too.
- If one of the numbers is floating point number then convert the other to floating point.
- If one of the numbers is a long integer then convert the other to a long integer. (Not applicable for Python 3.1)
- No previous rules applied, so both are integers, and Python leaves them unchanged.
In the above examples, we use type() function to determine the type of 2 different numbers: integer, float and complex.


That %s is the format specifier for a string. Several other specifiers are there. Each specifier acts as a placeholder for that type in the string; and after the string, the % sign outside of the string indicates that after it, all of the values to be inserted into the format specifier will be presented there to be used in the string.
print is a function—a special name that you can put in your programs that will perform one or more tasks behind the scenes. Normally, you don’t have to worry about how it happens. In this case, the print function is an example of a built-in function, which is a function included as a part of Python, as opposed to a function that you or another programmer has written. The print function performs output—that is, it presents something to the user using a mechanism that they can see, such as a terminal, a window, a printer, or perhaps another device (such as a scrolling LED display).


Comments