Python built-in functions-digital correlation

Source: Internet
Author: User
Tags cmath

This article summarizes the built-in functions for numbers.

The numbers include int () , Long () , float () , complex () , which can be used to convert a numeric type. These functions also accept string arguments, which return the numeric value represented by the string. In addition Int () and long () can also accept a binary parameter when converting a string, but if it is a type conversion between numbers, the parameter is not available.

Later, Python introduced a new function, bool () , to convert the integer values 1 and 0 to the standard Boolean True and False.

In 2.7, you can convert almost any data type to a Boolean representation. The conversion relationship of its Boolean values refers to my description in the Boolean chapter.

Python consolidates types and classes in 2.2, and all of the built-in functions are transformed into factory functions. The so-called factory functions are values. These functions are class objects, and when they are called, they are given an instance of the class.

But there is no difference between the use and the function.

1. bool (obj)

Returns the Boolean value of the Obj object, which is the return value of the obj.__nonzero__ () method. The default value of an object without the __nonzero__ () method is True.

class Text ():     "  "    def__init__(self,value):        = value      def__nonzero__(self):        return= Text (123)   #  Instantiate print bool (a)   # to determine the Boolean value of the instance

2. int (obj, base=10)

Returns an integer representation of a string or numeric object. But when the argument is a string, you can use base to specify the binary, the default is 10, when obj is a number, that is, when the number of the type conversion between the time, the parameter is not available.

Non-numeric string error.

3. long (obj, base=10)

Returns a long integer representation of a character or data object. Other ibid.

Other parts are not shown.

Non-numeric string error.

4. float (obj)

Returns a floating-point representation of a string or data object. No binary parameters are optional.

Other parts are not shown.

Non-numeric string error.

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

Returns the plural representation of a string, or generates a complex object based on a given real number (real) and an optional imaginary part (IMAG).

Other parts are not shown.

Non-numeric string error.

Built-in function functions:

1. ABS (num)

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

ABS () returns the absolute value of the given parameter. If the argument is a complex number, it returns MATH.SQRT (Num.real2 + num.imag2).

  

  

2. coerce (NUM1, num2)

Convert NUM1 and num2 to the same type, and then return as a tuple.

Conversion rules:

1. If one operand is a complex number, the other operand is converted to a complex number.

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

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

4. Otherwise, both must be ordinary integers, without the need for type conversions.

Priority: Complex > Floating-point numbers > Long shaping > Integers

  

3. Divmod (NUM1, num2)

Division-the combination of the take-rest operation. Returns a tuple (num1/num2, num1% num2). Rounding of the quotient of floating-point and complex numbers (quotient of complex numbers taking only real parts)

  

4. Pow (NUM1, num2, mod=1)

Take the num2 of the NUM1, if the MoD parameters are provided, then the results of the calculation of the MoD to take the remainder operation.

  

  

5. round (FLT, ndig=0)

Accepts a floating-point number flt and rounds it, saving ndig decimal places. If the Ndig parameter is not provided, the default is 0 digits after the decimal point. (integers can be, but it doesn't really make sense)

  

  

Note the difference between int (), round (), Math.floor (), and these several functions:

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

2. Function floor () Gets an integer close to the original number but less than the original number. (return value is floating point)

3. Function round () Gets an integer close to the original number. (return value is floating point)

  

Functions that are used only for integers:

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

These functions are divided into two classes, one for the binary conversion and the other for ASCII conversion.

1. Binary conversion function

Oct (num)

Converts an integer (any size) to an octal string. The result is a valid Python expression.

Hex (num)

Converts an integer (any size) into a lowercase hexadecimal string prefixed with ' 0x '.

2.ASCII conversion function

  Python also provides a conversion function between the ASCII (US standard Information Interchange Code) code and its sequence value. Each character corresponds to a unique integer (0-255). This number is constant for all computers that use the ASCII table. This guarantees the consistency of the program behavior between the different systems.

chr (num)

The function accepts a single-byte integer value that returns a string whose value is the corresponding character.

  

Ord (CHR)

Accepts a character and returns its corresponding integer value. Is the inverse of the above method.

unichr (num)

Accepts Unicode code values and returns their corresponding Unicode characters. The range of code values accepted depends on whether your Python is built on ucs‐2 or ucs‐4.

The implementation of random numbers:

The implementation of random numbers relies on the random module.

The module contains multiple pseudo-random number generators, all with the current timestamp as a random number seed. This allows you to start working whenever you load the module. The functions commonly used in this module are listed below:

Random.randrange ()

It takes the same parameters as the range () function and randomly returns an entry for the range ([start,]stop[,step]) result.

Import Random  Print Random.randrange (ten) print random.randrange (print) Random.randrange (1, 2)print random.randrange (1, 10, 2)

Random.uniform (A, b)

Almost the same as Randint (A, b), but it returns a floating-point number between the two (excluding the range cap).

Import Random  Print 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 () is only the lower limit constant equals 0.0, the upper limit is equal to 1.0.

  

random.choice (seq)

Returns an element of a given sequence at random.

Import= [1, 2, 3]print  random.choice (a)print  random.choice (a)  Print random.choice (a)

  

Other mathematical types related modules:

Decimal decimal floating-point arithmetic class decimal

Array of efficient numeric arrays (characters, integers, floating-point numbers, etc.)

Math/cmath standard C library mathematical operation function. General mathematical operations in the match module, complex operations in the Cmath module
The function implementation of the operator numeric operator. For example, Operator.sub (M,n) is equivalent to M-n.

......

Interested in self-understanding

Python built-in functions-digital correlation

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: info-contact@alibabacloud.com 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.