Python built-in functions-number-related, python function number

Source: Internet
Author: User
Tags mathematical functions

Python built-in functions-number-related, python function number

This article summarizes the built-in functions related to numbers.

Numbers include int (), long (), float (), and complex (). These functions can be used to convert numeric types. At the same time, these functions also accept string parameters and return the values represented by the string. In addition, int () and long () can also accept a hexadecimal parameter when converting a string, but if it is a type conversion between numbers, this parameter is not available.

Later, python introduced a new function bool (), which is used to convert integer 1 and 0 to standard boolean values True and False.

In 2.7, almost all data types can be converted to boolean values. For the Conversion Relationship of its Boolean value, refer to my description in Boolean.

Python has integrated types and classes in 2.2, and all the above built-in functions are converted into factory functions. The so-called factory function is that the values of these functions are class objects, and when they are called, they all get a class instance.

However, it is no different from the function in use.

1. bool (obj)

Returns the Boolean value of the obj object, that is, the return value of the obj. _ nonzero _ () method. The default value of the object without the _ nonzero _ () method is True.

Class Text (): "Custom Boolean test class" def _ init _ (self, value): self. value = value def _ nonzero _ (self): return Falsea = Text (123) # instantiate print bool (a) # judge the Boolean value of the Instance


2. int (obj, base = 10)

Returns the integer representation of a string or numeric object. However, when the parameter is a string, you can use base to specify the base. The default value is decimal. When obj is a number, that is, when the numbers are converted to different types, this parameter is unavailable.

Non-numeric string error.


3. long (obj, base = 10)

Returns a long integer representation of a character or data object. Others are the same as above.

Other parts are not demonstrated.

Non-numeric string error.


4. float (obj)

Returns the floating point representation of a string or data object. No hexadecimal parameters are optional.

Other parts are not demonstrated.

Non-numeric string error.


5. complex (str)/complex (real [, imag = 0])

Returns the plural representation of a string, or generates a plural object based on the given real number and an optional virtual number (imag.

Other parts are not demonstrated.

Non-numeric string error.


Built-in function:

1. abs (num)

  Num indicates that the parameter must be a number, which is not repeated below.

Abs () returns the absolute value of a given parameter. If the parameter is a complex number, math. sqrt (num. real2 + num. imag2) is returned ).




2. coerce (num1, num2)

Converts num1 and num2 to the same type, and returns the result in the form of a tuples.

Conversion rules:

1. If one operand is a plural value, the other operand is converted to a plural value.

2. Otherwise, if one operand is a floating point number, and the other operand is converted to a floating point number.

3. Otherwise, if one operand is a long integer, the other operand is converted to a long integer.

4. Otherwise, the two must be common integers without type conversion.

Priority: plural> floating point> long integer> integer



3. divmod (num1, num2)

Division-a combination of remainder operations. Returns a tuple (num1/num2, num1 % num2 ). Deprecated the operator of the floating point number and the plural number (the operator of the plural number takes only the real number)



4. pow (num1, num2, mod = 1)

Obtain the num2 power of num1. If the mod parameter is provided, the computation result is used to perform the remainder operation on the mod.




5. round (flt, ndig = 0)

Accept a floating point flt and round it to five to save the ndig decimal places. If the ndig parameter is not provided, the default value is 0 after the decimal point. (Integers are acceptable, but they do not have any practical significance)



Note the differences between int (), round (), and math. floor () functions:

1. the int () function directly truncates the fractional part. (Return value is an integer)

2. function floor () returns an integer close to the original number but smaller than the original number. (Return Value: floating point number)

3. The function round () returns an integer close to the original number. (Return Value: floating point number)





Only integer functions:

In addition to built-in functions for all numeric types, Python also provides built-in functions (Standard integers and long integers) that only apply to integers ).

These functions are divided into two types: one for hexadecimal conversion and the other for ASCII conversion.

1. hexadecimal conversion functions

Oct (num)

SetIntegerConverts a string of any size into an octal string. The result is a valid Python expression.


Hex (num)

SetIntegerConverts a string of any size to a lowercase hexadecimal string with a prefix of '0x '.


2. ASCII conversion functions

  Python also provides conversion functions between ASCII (American standard information interchange code) codes and their sequential values. Each character corresponds to a unique INTEGER (0-255 ). This value remains unchanged for all computers that use ASCII tables. This ensures the consistency of program behavior between different systems.

Chr (num)

The function accepts a single byte.IntegerReturns a string whose value is a character.


Ord (chr)

Returns the integer corresponding to a character. Is the inverse operation of the above method.


Unichr (num)

Returns the corresponding Unicode character. The accepted code value range depends on whether your Python is built on ucs‐2 or ucs‐4.




Random Number implementation:

The random number implementation depends on the random module.

This module contains multiple pseudo-random number generators, all of which use the current timestamp as the random number seed. In this way, you can start working at any time as long as you load this module. Common functions in this module are listed below:

Random. randrange ()

It accepts the same parameters as the range () function and returns a random result of range ([start,] stop [, step.

import randomprint random.randrange(10)print random.randrange(10)print random.randrange(1, 10, 2)print random.randrange(1, 10, 2)


Random. uniform (a, B)

It is almost the same as randint (a, B), but it returns a floating point number (excluding the upper limit of the range) between the two ).

import randomprint random.randint(1,10)print random.randint(1,10)print random.uniform(1,10)print random.uniform(0.1,0.9)


Random. random ()

Similar to uniform (), the lower limit is always 0.0, and the upper limit is always 1.0.


Random. choice (seq)

Random return givenSequence.

import randoma = [1, 2, 3]print random.choice(a)print random.choice(a)print random.choice(a)


Other mathematical modules:

Decimal Decimal floating point operation

Array efficient numeric array (character, integer, floating point, etc)

Math/cmath Standard C library mathematical functions. Regular mathematical operations are performed in the match module, while complex operations are performed in the cmath module.
Operator numeric operator function implementation. For example, operator. sub (m, n) is equivalent to m-n.


If you are interested


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.