Python BASICS (10)-numbers, python basics-Numbers

Source: Internet
Author: User
Tags bitwise operators floor division integer division

Python BASICS (10)-numbers, python basics-Numbers

The topic of this article is numbers in Python. Describes each numeric type in detail, the various operators they apply, and the built-in functions used to process numbers. At the end of the article, I briefly introduced several modules used to process numbers in the standard library.


Numeric type

Numbers provide scalar storage and direct access. It is a type that cannot be changed, that is, the value of a change number will generate a new object. Of course, this process is transparent to both programmers and users, and does not affect the way software is developed. Python supports multiple numeric types: integer, long integer, Boolean, double-precision floating point, decimal floating point, and plural.
Create a value object and assign values to it
(Numeric object)
Creating a value object is as simple as assigning a value to a variable:

>>> anInt = 1
>>> along = -555555555555L
>>> afloat = 3.141595468565
>>> acomplex = 1.334 + 4.5433j
Update digital objects
By (re) assigning a numeric object, you can "update" a numeric object. The reason we put quotes around these two updates is because you haven't actually updated the original value of the object. This is because numeric objects are immutable objects. Python's object model is somewhat different from the regular object model. What you think of an update is actually generating a new numeric object and getting a reference to it. In the process of learning programming, we have been receiving such an education. A variable is like a box containing the value of the variable. In Python, a variable is more like a pointer to a box that holds the value of the variable. For immutable types, you cannot change the contents of the box, but you can point the pointer to a new box. Every time you assign another number to a variable, you actually create a new object and assign it to the variable. (Not just numbers, this is true for all immutable types)

anInt + = 1
aFloat = 2.718281828
Tested with the following code:

>>> anInt = 1
>>> id (anInt)
>>> anInt + = 1
>>> id (anInt)
How to delete digital objects
According to Python's rules, you can't really delete a numeric object, you just don't use it anymore. If you actually want to delete a reference to a numeric object, use the del statement. After you delete a reference to an object, you can no longer use the reference (variable name) unless you assign it a new value. If you try to use an object reference that has already been deleted, a NameError exception is raised.

del anInt
del aLong, aFloat, aComplex
The four main types of numbers in Python
Python has several integer types. A Boolean type is an integer type with only two values. A regular integer is an integer that is recognized by most modern systems. Python also has long integer types. However, it represents much larger values than C long integers. Let's take a look at these types first, and then look at the operators and built-in functions for Python integer types.

1.1 Boolean
Python supports boolean types since version 2.3. There are only two values for this type, namely Boolean True and False.
1.2 Standard integer types
Python's standard integer types are the most common number types. On most 32-bit machines, the standard integer type ranges from -231 to 231-1, which is -2,147,483,648 to 2,147,483,647. If you compile Python with a 64-bit compiler on a 64-bit machine, the integers on this system will be 64-bit. Here are some examples of Python's standard integer type objects:
0101 84 -237 0x80 017 -680 -0X92
Python's standard integer types are equivalent to C's (signed) longs. Integers are usually expressed in decimal, but Python also supports octal or hexadecimal representation of integers. If an octal integer starts with the number "0", a hexadecimal integer starts with "0x" or "0X".
1.3 Long Integer
What we have to mention about Python long integer types is that they should not be confused with long integer types in C or other compiled languages. The long integers for those languages are typically 32-bit or 64-bit. The value that Python's long integer type can express is only related to the (virtual) memory size supported by your machine. In other words, Python can easily express very large, very large integers. Long integer types are a superset of standard integer types. Long integer types are useful when your program needs to use larger integers than standard integer types. Add an L (either uppercase or lowercase) after an integer value to indicate that the integer is a long integer. This integer can be decimal, octal, or hexadecimal. Here are some examples of long integers:
16384L -0x4E8L 017L -2147483648l 052144364L
Edit By Vheavens
Edit By Vheavens
Core style: Use the capital letter "L" to represent long integers. Currently, integers and long integers are slowly unifying. You can only see "L" when calling the repr () function on long integers. You cannot see L by calling the str () function on an integer object. For example:

>>> aLong = 999999999l
>>> aLong
>>> print aLong
1.4 Integer and Long Integer

These two integer types are gradually unifying into one. Before Python 2.2, standard integer type objects would overflow the range of values (such as the numbers greater than 232 mentioned above), but since Python 2.2 there is no such error.

>>> 9999 ** 8
Traceback (most recent call last):
File "<stdin>", line 1, in?
OverflowError: integer exponentiation
Python 2.2
>>> 9999 ** 8
Double precision floating point
Floating point numbers in Python are similar to the double type in C. They are double-precision floating point numbers and can be expressed in direct decimal or scientific notation. Each floating-point number occupies 8 bytes (64 bits), and fully complies with the IEEE754 specification (52M / 11E / 1S), of which 52 bits are used to indicate the base and 11 bits are used to indicate the exponent (the range that can be expressed is approximately Plus or minus 10 to the power of 308.25), the remaining one bit represents the sign. This looks perfect, however, the actual accuracy depends on the machine architecture and the compiler that created the Python interpreter. Floating point values usually have a decimal point and an optional suffix e (uppercase or lowercase for scientific notation). You can use positive (+) or negative (-) between e and the exponent to indicate the exponential sign (if the number is positive, you can omit the sign). Here are some examples of typical floating-point values:

0.0 -777. 1.6 -5.555567119 96e3 * 1.0
4.3e25 9.384e-23 -2.172818 float (12) 1.000000001
3.1416 4.2E-10 -90. 6.022e23 -1.609E-19
The combination of a real number and an imaginary number constitutes a complex number. A complex number is a pair of ordered floating-point numbers (x, y). Expressed as x + yj, where x is the real part and y is the imaginary part. Gradually the plural has been widely used in daily computing, machinery, electronics and other industries. As researchers continue to repeatedly make tools for complex numbers, in the 1.4 version of Python a long time ago, complex numbers finally became a true Python data type.
Here are a few concepts about complex numbers in Python:

Imaginary numbers cannot exist on their own, they always form a complex number with a real value part of 0.0.

Complex numbers consist of real and imaginary parts

Syntax for imaginary numbers: real + imagj

Both the real and imaginary parts are floating point numbers

The imaginary part must have the suffix j or J.

1. Built-in attribute of plural
Complex objects have data attributes, which are the real and imaginary parts of the complex number, respectively. Complex numbers also have a conjugate method, which can be called to return the complex conjugate complex number object.

Plural attribute
Property Description
num.real the real part of the complex number
num num.imag the imaginary part of the complex number
num.conjugate () returns the complex conjugate of the complex number

>>> c = 2.3 + 2.5j
>>> c.real
>>> c.imag
>>> c.conjugate ()
Numeric types can perform a variety of operations. From standard operators to numeric operators, there are even specialized integer operators.
5.5.1 Mixed mode operators
Python supports the addition of different number types. When an integer is added to a floating point number, the system decides whether to use integer addition or floating point addition (there are no mixed operations in practice). Python uses number type coercion to solve the problem of inconsistent number types, which means that it will coerce one operand to the same data type as another operand. This operation is not arbitrary, it follows the following basic rules:

First, if both operands are of the same data type, no type conversion is necessary. Only when the two operand types are inconsistent will Python check whether one operand can be converted to another type of operand. If possible, convert it and return the result of the conversion.

Since some conversions are not possible, than if a complex number is converted to a non-complex type, a floating point number is converted to an integer, etc., the conversion process must follow several rules. To convert an integer to a floating point number, just add .0 after the integer. To convert a non-complex number to a complex number, you only need to add an imaginary part of "0j".

The basic principles of these type conversions are: integers are converted to floating-point numbers, and non-complex numbers are converted to complex numbers. The coerce () method is described in the Python Language Reference:
If one operand is complex, the other operand is converted to a complex number.
Otherwise, if one operand is a floating point number, the other operand is converted to a floating point number.
Otherwise, if one operand is a long integer, the other operand is converted to a long integer;
Otherwise, both must be ordinary integers without type conversion.
Conversions between numeric types are performed automatically, and programmers do not need to code and handle type conversions themselves. Python provides coerce () built-in functions to help you achieve this conversion.

See the following flowchart to illustrate the rules for coercion:

Arithmetic operator

Python supports the unary operators (+) and minus (-), the binocular operators, +,-, *, /,%, and **, which respectively represent addition, subtraction, multiplication, division, and remainder. , And power operations. As of Python 2.2, a new integer division operator // has also been added.

Traditional division
In the case of integer division, traditional division rounds off the decimal part and returns an integer (floor division). If one of the operands is a floating-point number, the actual division is performed. This behavior is common in many languages, including Python. Look at the following example:

>>> 1/2 # perform integer result (floor) # floor division
>>> 1.0 / 2.0 # returns actual quotient # true division
True division

Division always returns the true quotient, regardless of whether the operand is an integer or a floating point number. This will be the standard behavior of division in future versions of Python. This can also be done by executing the from __future__ import division instruction at this stage.

>>> from __future__ import division
>>> 1/2 # returns real quotient
>>> 1.0 / 2.0 # returns real quotient
Floor except

Starting from Python 2.2, a new operator // has been added to perform floor division: // Division is always rounded off the decimal part regardless of the numeric type of the operand, and returns a sequence of numbers that is smaller than the real quotient The closest number.

>>> 1 // 2 # floors result, returns integer # floor division, returns integer
>>> 1.0 // 2.0 # floors result, returns float # floor division, returns float
>>> -1 // 2 # move left on number line # returns an integer smaller than –0.5, which is -1
Power operation
The precedence relationship between the power operator and the unary operator is special: the power operator has lower priority than the unary operator of its left operand, and has higher priority than the unary operator of its right operand. Due to this feature you will find two ** in the arithmetic operator table. Here are some examples:

>>> 3 ** 2

>>> -3 ** 2 # ** has higher priority than the left-
>>> (-3) ** 2 # brackets increase the priority of-

>>> 4.0 ** -1.0 # ** Priority is lower than on the right-
In the second case, the interpreter first calculates 3 ** 2 and then takes the opposite number. We need to add parentheses to "-3" to get the result we want. In the last example, the result is 4 ** (-1), which is the result obtained according to the specified priority.

>>> 4 ** -1
Traceback (innermost last):

File "<stdin> ", line 1, in?
ValueError: integer to the negative power
Here are more examples of Python numerical operations:

>>> -442-77 -519 >>> Edit By Vheavens Edit By Vheavens >>> 4 ** 3 64 >>> >>> 4.2 ** 3.2 98.7183139527 >>> 8/3 2 >>> 8.0 / 3.0 2.66666666667 >>> 8% 3 2 >>> (60.-32.) * (5. / 9.) 15.5555555556 >>> 14 * 0x04 56 >>> 0170/4 30 >>> 0x80 + 0777 639 >> > 45L * 22L 990L >>> 16399L + 0xA94E8L 709879L >>> -2147483648L-52147483648L -54294967296L >>> 64.375 + 1j + 4.23-8.5j (68.605-7.5j) >>> 0 + 1j ** 2 # same as 0+ (lj ** 2) (-1 + 0j) >>> 1 + 1j ** 2 # same as 1+ (lj ** 2) 0j >>> (1 + 1j) ** 2 2j View Code
* Bitwise operator (only for integers)

Python integers support standard bit operations: negation (~), bitwise AND (&), or (|), XOR (^), left shift (<<), and right shift (>>). Python handles bitwise operations like this:
Negative numbers are treated as two's complement of positive numbers.
Shifting left and right by N bits is equivalent to 2 powers of N without overflow checking: 2 ** N.
For long integers, the bit operator uses a modified form of two's complement, which allows the sign bit to be extended to the left indefinitely. The negation (~) operation has the same priority as the numeric monocular operator and is the highest priority of all bit operators. Left and right shift operations have the second highest priority, but are lower than addition and subtraction operations. AND, OR, and XOR operations have the lowest priority. All bitwise operators are listed in order of priority in Table 5.4

Built-in functions and factory functions
Standard type functions
cmp (), str () and type () built-in functions. These functions can be used for all standard types. For numeric objects, these functions compare the size of two numbers, convert the number to a string, and return the type of the number object.

Conversion factory function
The functions int (), long (), float (), and complex () are used to convert other numeric types to their corresponding numeric types. Since Python 2.3, a new member has been added to Python's standard data types: the Boolean type. Since then true and false now have constant values i.e. True and False (no longer 1 and 0)

Here are some examples of using built-in functions:

>>> int (4.25555)
>>> long (42)
>>> float (4)
>>> complex (4)
(4 + 0j)
>>>>>> complex (2.4, -8)
>>> complex (2.3e-10, 45.3e4)
(2.3e-10 + 453000j)
Python has five arithmetic built-in functions for numerical operations: abs (), coerce (), divmod (), pow (), pow (), and round (). We will go through each of these functions and give some useful examples:

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

coerce () returns only a tuple containing two numeric elements after type conversion

The divmod () built-in function combines division and remainder operations and returns a tuple containing the quotient and the remainder. For integers, the return value is the result of the floor division and remainder operations. For floating point numbers, the quotient returned is math.floor (num1 / num2), and for complex numbers, the quotient is ath.floor ((num1 / num2) .real).

>>> divmod (10, 3)
(3, 1)
>>> divmod (10, 2.5)
(4.0, 0.0)
>>> divmod (2.5, 10)
(0.0, 2.5)
>>> divmod (2 + 1j, 2.3 + 4.3j)
(0j, (2 + 1j))
round () is used to round the floating point number. It has an optional number of decimals parameter. If no decimal argument is provided, it returns the nearest integer (but still a floating point type) to the first argument. The second parameter tells the round function to round the result to the specified number of digits after the decimal point.

>>> round (3)
>>> round (3.154)
>>> round (3.499999, 1)

>>> import math
>>> for n in range (10):
    print round (math.pi, n)

Built-in functions for numerical operations:

Function function
abs (num) returns the absolute value of num
coerce (num1, num2) converts num1 and num2 to the same type and returns them as a tuple
divmod (num1, num2) division-a combination of remainder operations. Returns a tuple (num1 / num2, num1% num2). Round the quotient of floating point and complex numbers
pow (num1, num2, mod = 1) takes num2 to the power of num2. If mod is provided, the calculation result is then used to perform the remainder operation on mod.
round (flt, ndig = 0) takes 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.
round () is only used for floating point numbers

Built-in functions that only work with integers:

Function operation
hex (num) converts a number to a hexadecimal number and returns it as a string
oct (num) converts a number to an octal number and returns it as a string
chr (num) converts the number of ASCII value to ASCII character, the range can only be 0 <= num <= 255
ord (chr) accepts an ASCII or Unicode character (a string of length 1) and returns the corresponding ASCII or Unicode value.
unichr (num) accepts a Unicode code value and returns its corresponding Unicode character. The range of accepted code values depends on whether your Python is built on UCS‐2 or UCS‐4


Python generates 10 random numbers within 11000 and the sum of ten numbers is less than 5000 to output the result
from random import randint
num = []
i = 0
while True:
num.append (randint (0,1000))
i + = 1
if i == 10:
if sum (num) <5000:
print num
i = 0
num = []
How to calculate the sum of all even numbers from 1 to 10 with python?

sum ([i for i in range (1, 11) if i% 2 == 0])

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.