Number types for Python

Source: Internet
Author: User
Tags floor division truncated
The following small series for everyone to bring a brief talk about the number types and processing tools in Python. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.

Numeric type tools in Python

Python provides many advanced digital programming support and objects for more advanced work, with complete tools for numeric types including:

1. Integers and floating-point types,

2. Plural,

3. Fixed-precision decimal number,

4. Rational score,

5. Collection,

6. Boolean type

7. Infinite integer Precision

8. Various digital built-in functions and modules.

Base Number Type

Two basic types are available in Python: integer (positive integer negative integer) and floating point number (note: Numbers with fractional parts), where we can use a number of binary integers in Python. and integers can be used with infinite precision.

The representation of an integer appears as a decimal digit string, with a floating-point number represented by a decimal point or by using scientific notation E. In the Python2 version, integers are also divided into general integers (32-bit) and long integers (infinite precision), with long integers ending in L. With the Python3, there is only one form of integer, with infinite precision.

Of course, the integers in Python also have binary (0bxxxxxxxx), octal (0oxxxxxxxx), and hexadecimal (0x xxxxxxxx) forms.

Conversion of decimal number to other binary:


S=16print (Bin (s)) print (Oct (s)) print (hex (s)) Run Result: 0b100000o200x10


Print (' {0:o},{1:x},{2:b} '. Format (16,16,16)) print ('%o,%x,%x '% (16,16,16)) Run Result: 20,10,1000020,10,10

Other conversions into decimal:


A=int (' 0b10000 ', 2) b=int (' 0o20 ', 8) c=int (' 0x10 ', +) print (a) print (b) print (c) Run Result: 161616


Print (' 16161616 ') print (eval (' 0b10000 ')) Print (eval (' 0o20 ')) Print (eval (' 0x10 ')) Run Result:

Python expression operators

Expressions are written with mathematical symbols and manipulation symbols, and the following table is the Python expression operator and program:

Operator Description
Yield Generator function Send protocol
Lambda args:expression Generating anonymous functions
X if y else Z Three-dimensional expression
X or Y Logical OR (existence of short-circuit algorithm)
X and Y Logic and (existence of short-circuit algorithm)
Not X Logical Non-
X in Y, x not in Y Member relationships
X is y, X was not y Object Entity Test
X<y,x<=y,x>y,x>=y,x==y,x!=y Comparison size
X|y Bit or, set merge set
X^y Bit XOR, set symmetry difference
X&y Bit and, set intersection
X<<y,x>>y Move left or right y position
X+y,x-y Add and subtract, merge delete
x*y,x%y,x/y,x//y Multiply, take the remainder, except, the floor
-x,+x One-dollar subtraction
~x bitwise complement (negation)
X**y Power operation
X[i] Index, Function call
X[I:J:K] Sharding
X (...) Calling functions
X.attr Call Properties
(...) Tuples, expressions, generators
[...] List, list resolution
{...} Dictionary, Collection, collection, and dictionary parsing

Note : Operators in Python2 and Python3 slightly different, python2 is not equal to use! = or "<> to indicate, in Python3 <> method is canceled, not equal to use!" = to represent.

X<y<z is equivalent to X<y and Y<z,

Mixed types can be used in python2, and comparisons of mixed type sizes in Python3 are error-


PYTHON2A = 1 > ' A ' Print a run result: False


Python3<br>a=1 > ' A ' Print (a) Run Result: Traceback (most recent call last): File "c:/users/jeff/pycharmprojects/ python_file/practice/prac2.py ", line-up, in <module> a=1 > ' A ' typeerror:unorderable types:int () > str ()

The table above is also the program's priority table, top-down, higher priority, of course, if you want to change the priority, if you use parentheses to do. Parentheses are often used in Python digital operations, and not only does it force programs to run in the order you want them, but it also increases the readability of the program.

Mixed type

What does this mean by mixing numeric types, such as the result of adding integers and floating-point numbers?

In Python, you first convert the standby object to the type of the most complex operand, and then do the same type of object for the mathematical operation.


Print (1+0.2) Run Result: 1.2

Note: In addition, there are operator overloading functions in python such as ' + ', in addition to the number addition operation, the string concatenation also applies ' + '.

Digital display format

Because of some hardware limitations, digital displays can sometimes look strange, such as:


Operations on the command line >>>num = 1/3.0>>>num0.333333333333333333331 in pycharm print operation num = 1/3.0print (num) Run Result: 0.3333333333333333num = 1/3.0print (' {0:4.2f} '. Format (num)) #4是前面空格格数, 2 is reserved for the decimal place running result: 0.33

The form shown on the command line is called the default interactive echo, while print is called friendly echo, which is consistent with the display of Reper and STR:


>>>num = 1/3.0>>>repr (num) 0.333333333333333333331>>>str (num) 0.3333333333333333

Division: Traditional Division, Floor division, True Division and truncated division

Division is a very important change between Python2 and Python3.

One, division operator

Python has two division operators ' x/y ' and ' x//y ', where '/' is the traditional division in Python2, that is, omitting the fractional portion of a floating-point number, but showing an integer, in Python3, where division is the true division, that is, the fractional part is preserved regardless of type; Also known as floor division, omit the fractional part in Python3, leave the smallest divisible integer part, and if the operand is a floating-point number, the result displays floating-point numbers, the integers in the python2 are truncated, and the floating-point numbers perform the reserved floating-point numbers.

Example: in Python2:

In the Python3:

In Python2, if you want to use '/' in Python3, you need to call the module to complete and invoke the Pision module in Python2:

Truncation Division, like floor division, takes the nearest integer down, which makes it effective when negative, i.e. 2.5 is-3, not-2, and the math module needs to be called to get a real intercept:

Python also supports the calculation of complex numbers:

Compliex (REAL,IMAG) is also supported to create complex numbers.

For more complex calculation Reference module Cmath reference Manual.

-bit operation


X=1print (x<<2) print (x|2) print (x&2) print (x^2) Run Result: 33

Python3 use Bit_length to see the number of bits:


X=99print (Bin (x)) print (X.bit_length ()) print (Len (Bin (x))-2) Run Result: 0b110001177

Built-in Math tools

Math Module


Import Mathprint (Math.PI) print (MATH.E) print (Math.sin ()) Print (MATH.SQRT (144)) Print (POW (2,3)) print (ABS (-50)) Print (sum ()) print (max (+)) print (min ()) Running Result: 3.1415926535897932.718281828459045-0.04424267808507096512.0850631

There are four ways to intercept floating-point numbers:


Print (Math.floor (2.577)) print (Math.trunc (2.577)) print (round (2.577)) print (int (2.577)) Run Result: 2232

Random module

Get random number


Import Randomprint (Random.random ()) print (Random.randint (1,100)) Run Result: 0.953484522146717879

Other numeric types are introduced

In addition to the common integer and floating-point numbers, there are some other more common numeric types.

First, fractional numbers

Although learning python for some time, but do not really understand the difference between floating-point and decimal, in fact, decimal is a floating point in some degree, but he has a fixed number of digits and decimal point, in Python has a special module import decimal, from decimal import decimal.

Note: Floating point numbers lack accuracy.


Print (0.1+0.1+0.1-0.3) output results: 5.551115123125783E-17

I would like to see the brothers here may have panicked, and then use the Python interpreter to try it, and sure enough, the result is 5.551115123125783e-17, although very close to 0, but not 0. So the essence of floating-point type is lack of accuracy. To be precise, you need to call the From decimal import decimal.


From decimal import decimalprint (decimal (' 0.1 ') +decimal (' 0.10 ') +decimal (' 0.10 ')-decimal (' 0.30 ')) Run Result: 0.00

You can see that the addition of decimals is automatically promoted to the largest number of bits.

Note: Floating-point numbers create decimal objects, and because the floating-point numbers themselves may be inaccurate, the conversion produces more digits.


From decimal import decimalprint (Decimal.from_float (1.88)) print (Decimal.from_float (1.25)) Output Result: 1.879999999999999893418589635984972119331359863281251.25

Second, the score

Fractional types are very similar to decimals, and they all control precision by fixing the number of decimal places and specifying rounding or interception policies. Fractions are imported using the fraction module.


From fractions import fractionx=fraction (1,3) y=fraction (2,3) print (x+y) output: 1

Note: The limitations of floating-point numbers are particularly noticeable for values that cannot be accurately represented by a given finite number of digits in memory. Fractions and decimals are more accurate than floating-point numbers.

Three, the collection

Collections are unordered elements, and the order of printing is unordered, but there are no duplicate elements in the collection, so we often use collections to weigh, especially when it comes to working with numbers and databases.

We have two sets A and B:

The intersection of A and B is a.intersection (b) or A & B.

The difference between A and B is either a.difference (b) or a-a.

A and B are a.union (b) or a|b.

The inverse difference sets are a.symmetric_difference (b) or a^b with the symmetric difference set (and the set minus the intersection).

Merge to A.update (b), a.difference_update (b) Differential set and assign to a set

Delete element can be discard (element) or remove (element), pop () is randomly delete an element, add inserts an item.

Note: Set is a mutable data type, but the element inside the set must be an immutable data type.


X={' A ', ' C ', ' B '}y={' A ', ' G ', ' B '}z={' A '}print (' A ' in X ') print (x-y) print (x|y) print (x&y) print (x^y) print (z<y)


X={' A ', ' C ', ' B '}y={' A ', ' G ', ' B '}z={' A '}print (x.intersection (y)) print (X.union (y)) x.add (' s ') print (x) print (X.pop ()) X.update ({' W ', ' e ', ' O '}) print (x) print (x) Run result: {' A ', ' B '} {' C ', ' A ', ' B ', ' g '} {' A ', ' B ', ' C ', ' s '}a{' o ', ' C ', ' s ', ' W ', ' B ', ' E '} {' O ', ' C ', ' s ', ' W ', ' B ', ' E '}

Note: In Python {} is an empty dictionary, if you want to define an empty collection to use Set ().

If you add a mutable type such as a list, the collection will get an error.


X={' A ', ' C ', ' B '}l=[1,2,3]x.add (l) print (x) Run Result: Traceback (most recent call last): File "c:/users/jeff/pycharmprojects/ python_file/practice/prac2.py ", line 111, in <module> Print (X.add (l)) typeerror:unhashable type: ' List '

Add tuples correctly by adding a sequence.


X={' A ', ' C ', ' B '}l= (All-in-All) X.add (l) print (x) Run result: {' C ', ' B ', ' A ', (1, 2, 3)}

Defines a collection that is not operational by using the Frozenset definition.

Dictionary parsing:

Similar to list parsing, a collection is also an iterative object, so you can use a For loop traversal.


X={1,2,3}print ({i * * 2 for I in X}) run Result: {1, 9, 4}

Four, Boolean value

Python has a data type that has two values of ture and False.


Print (Type (true)) print (true = = 1) print (true is 1) print (true + 1) Run Result: <class ' bool ' >TRUEFALSE2

Sets and bool values, or more common types, are also involved in basic learning, and there is not much to write about here.

The numbers in Python are widely used in programming, and will learn more about Python's extended libraries in the future.

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: 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.