The Python introductory article digital _python

Source: Internet
Author: User
Tags abs arithmetic arithmetic operators bitwise bitwise operators chr object model stdin

Number Type

The numbers provide scalar storage and direct access. It is a type that cannot be changed, meaning that changing the value of a number generates a new object. Of course, this process is transparent to both the programmer and the user, and does not affect how the software is developed. Python supports a variety of numeric types: Integer, Long, Boolean, double-precision floating-point, decimal floating-point, and plural.
Create a numeric object and use it to assign values
(Numeric object)
Creating a numeric object is as simple as assigning a value to a variable:

Copy Code code as follows:

>>> anint=1
>>> along=-555555555555l
>>> afloat=3.141595468565
>>> acomplex=1.334+4.5433j

Update numeric objects

You can "update" a numeric object by assigning a value to a numeric object (re). The reason we add quotes to the update is that you don't actually update the original value of the object. This is because the numeric object is not a modified object. Python's object model is somewhat different from the general object model. What you think of as an update is actually generating a new numeric object and getting a reference to it. In the process of learning programming, we have been taught that the variable is like a box containing the value of the variable. In Python, a variable is more like a pointer to a box containing a variable value. You can't change the contents of a box for an immutable type, but you can point the pointer at a new box. Each time you assign another number to a variable, you actually create a new object and assign it to the variable. (not just numbers, for all immutable types, this is the case)

Copy Code code as follows:

Anint + 1
Afloat = 2.718281828

Test with the following code:

Copy Code code as follows:

>>> anint=1
>>> ID (anint)
10416152
>>> anint+=1
>>> ID (anint)
10416140

How to delete a numeric object

By Python's law, 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 attempt to use a reference to an object that has already been deleted, a Nameerror exception is thrown.

Copy Code code as follows:

Del Anint
Del along, afloat, Acomplex

Four main types of numbers in Python

1. Integral type

Python has several integer types. A Boolean type is an integral type with only two values. Conventional integers are integral types that are recognized by most modern systems. Python also has long integer types. However, it represents a value that is much larger than a long integer in the C language. Let's look at these types first and then look at the operators and built-in functions that are used for Python integer types.

1.1 Boolean type

Python supports Boolean types starting with version 2.3. The range of values for this type is only two values, that is, the Boolean value True and the Boolean value False.

1.2 Standard integer types

The standard Python integer type is the most common numeric type. On most 32-bit machines, the range of values for a standard integer type is 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 integer on this system will be 64 bits. Here are some examples of Python standard integer type objects:
0101 84-237 0x80 017-680-0x92
Python standard integer types are equivalent to the (signed) long integer type of C. Integers are generally expressed in decimal, but Python also supports octal or hexadecimal notation for integers. If the octal integer begins with the number "0", the hexadecimal integer begins with "0x" or "0X".

1.3 Long Integral type

About Python Long integer types What we must mention is that you do not confuse it with the long integer type of C or other compiled languages. The long integers of those languages typically have a range of 32-bit or 64-bit values. The number of long integer types that python can express is related only to the size of your machine's supported (virtual) memory, in other words, Python can easily express large, large integers. Long integer types are superset of standard integer types, and long integer types are useful when your program needs to use integers larger than the standard integer type. 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:

Copy Code code as follows:

16384l-0x4e8l 017l-2147483648l 052144364L
299792458l 0xdecadedeadbeefbadfeeddeal-5432101234l
Edit by Vheavens
Edit by Vheavens

Core style: Long integers in uppercase letters "L", the current integer and long integer are slowly being unified, you only have the opportunity to see "L" When you call the Repr () function on long integers, if you call the STR () function on a long integer object, you cannot see L. Examples are as follows:

Copy Code code as follows:

>>> along = 999999999l
>>> along
999999999L
>>> Print along
999999999

1.4 Unification of integral type and long integer type

The two types of integers are gradually being unified into one. Before Python 2.2, a standard integer type object that exceeded the value range would overflow (for example, the above 232 number mentioned above), but there was no such mistake since Python2.2.

Copy Code code as follows:

>>> 9999 * * 8
Traceback (most recent call last):
File "<stdin>", line 1, in?
Overflowerror:integer exponentiation
Python 2.2
>>> 9999 * * 8
99920027994400699944002799920001L

Double-precision floating point numbers

Floating-point numbers in Python are similar to the double type in C, which is a double-precision floating-point number that can be represented by a direct decimal or scientific notation. Each floating-point number occupies 8 bytes (64 bits) and is fully compliant with the IEEE754 number specification (52M/11E/1S), where 52 bits are used to represent the bottom, 11 bits are used to represent the exponent (the range is about 10 of positive or negative 308.25), and the remaining bits represent symbols. This looks pretty perfect, however, the actual precision relies on the machine architecture and the compiler that creates the Python interpreter. Floating-point values usually have a decimal point and an optional suffix e (uppercase or lowercase, which means scientific notation). either positive (+) or negative (-) indicators can be used between e and exponents to denote positive and negative (positive) signs of the exponent. Here are some examples of typical floating-point values:

Copy Code code as follows:

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

Plural

A 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). represented as X + YJ, where x is the real part, and y is the imaginary fraction. Gradually the complex number in the day-to-day operations, machinery, electronics and other industries have been widely used. Since some researchers have repeatedly made tools for complex operations, in the Python1.4 version of a long time ago, complex numbers have finally become a true Python data type.
Here are several concepts about complex numbers in the Python language:

Imaginary numbers cannot exist alone, and they always form a complex number together with a real part of a value of 0.0.

The complex number is composed of the real part and the imaginary part

syntax to represent imaginary numbers: REAL+IMAGJ

Both real and imaginary parts are floating point numbers

The imaginary part must have a suffix of J or J.


1. The built-in properties of complex numbers
Plural objects have data attributes, which are the real and imaginary parts of the complex number, respectively. A complex number also has a conjugate method, which can be called to return a conjugate plural object of that complex number.

Complex Number Property

Attribute description
Num.real the real part of the plural
Num Num.imag The imaginary part of the complex number
Num.conjugate () returns the conjugate complex number of the complex number

Copy Code code as follows:

>>> c=2.3+2.5j
>>> C.real
2.3
>>> C.imag
2.5
>>> C.conjugate ()
(2.3-2.5j)

Operator

Numeric types can perform multiple operations. From standard operators to numeric operators, there are even specialized integer operators.

5.5.1 Mixed Mode operator

Python supports the addition of different numeric types. When an integer and a floating-point number are added, the system determines whether to use integer addition or floating-point number addition (there is no mixed operation in fact). Python uses the method of casting numeric types to solve the problem of inconsistent numeric types, which means that it forces the conversion of an operand to the same data type as the other operand. This is not a random operation, it follows the following basic rules:

First, if two operands are of the same data type, there is no need for type conversions. Python checks whether an operand can be converted to an operand of another type only if the two operand types are inconsistent. If you can, convert it and return the result of the transformation.

Because some conversions are not possible, the conversion process must adhere to several rules, rather than converting a complex number to a non-plural type, converting a floating-point number to an integer, and so on. To convert an integer to a floating-point number, just add a. 0 to the back of the integer. To convert a non-plural 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. This describes the coerce () method in the Python language reference:
If one operand is a complex number, 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 of the operands is a long integer, the other operand is converted to a long integer;
Otherwise, the two must all be normal integers, without type conversion.
Conversions between numeric types are automatic, and programmers do not have to encode their own to handle type conversions. Python provides coerce () built-in functions to help you implement this transformation.

See the following flowchart illustrating the rules for casting:

Arithmetic operators

Python supports the monocular operator plus (+) and minus sign (-), binocular operators, +,-,*,/,%, and * *, which represent addition, subtraction, multiplication, division, remainder, and power operations, respectively. A new division operator//is added from the Python2.2.

Traditional Division
If it is an integer division, traditional division will give away the fractional part and return an integer (floor divide). If one of the operands is a floating-point number, the real division is performed. Many languages, including the Python language, are this behavior. Look at the following example:

Copy Code code as follows:

>>> 1/2 # Perform integer result (floor) # Floor Removal
0
>>> 1.0/2.0 # returns actual quotient# real division
0.5

the real Division

The division operation always returns the real quotient, regardless of whether the operand is an integer or a floating-point number. In a future version of Python, this would be the standard behavior for division operations. This can also be done at this stage by executing the From __FUTURE__ Import Division directive.

Copy Code code as follows:

>>> from __future__ Import Division
>>>
>>> 1/2 # returns real quotient
0.5
>>> 1.0/2.0 # returns real quotient
0.5

Floor except

Starting with Python 2.2, a new operator//has been added to perform the floor except://Division No matter what numeric type the operand is, always give away the decimal part and return the nearest number in the number sequence that is smaller than the real quotient.

Copy Code code as follows:

>>> 1//2 # Floors result, returns integer # floor except, return integer
0
>>> 1.0//2.0 # Floors result, returns float # floor In addition, return floating-point numbers
0.0
>>> 1//2 # Move left on number line# returns a smaller integer than –0.5, which is-1
-1

Power operation

The priority relationship between the power operator and the unary operator is special: The exponentiation operator has a lower precedence than the unary operator of its left-hand operand, which is higher than the unary operator of the right-hand operand, and because of this feature you will find two * * * in the arithmetic operator table. Here are a few examples:

Copy Code code as follows:

>>> 3 * * 2
9
>>> 3 * * * 2 # * * Priority is higher than left-
-9
>>> (-3) * * * 2 # Plus bracket Increase-priority
9
>>> 4.0 * * *-1.0 # * * * priority is lower than the right side-
0.25

In the 2nd case, the interpreter first calculates the 3**2 and then the opposite number, we need to add parentheses to the "3" to get the result we want. In the final example, the result is 4** (-1), which is the result of the given priority.

Copy Code code as follows:

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

File "<stdin>", line 1, in?
Valueerror:integer to the negative power

Here are more examples of Python numerical operations:

Copy Code code as follows:

>>>-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
>>> * 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

* Bitwise operator (for integers only)

Python integers support standard bit operations: reverse (~), bitwise-AND (&), or (|) and XOR (^) and left (<<) and right-shift (>>). Python handles bitwise operations like this:
Negative numbers are treated as positive 2-in-complement.
The left and right shifts n bits are equivalent to the N-Power operations of 2 without overflow checking: 2**n.
For long integers, the bitwise operator uses a modified 2-complement form that allows the symbol bits to extend infinitely to the left. The priority of the inverse (~) operation is the same as the digital monocular operator, which is the highest priority in all bitwise operators. The precedence of the left and right shifts, but less than the addition and subtraction operation. With, or, XOR or operation is the lowest priority. All bitwise operators are listed in Table 5.4 by priority

Built-in functions and factory functions

Standard type function
CMP (), str (), and type () built-in functions. These functions can be used with all standard types. For numeric objects, these functions compare the two-digit size, convert the number to a string, and return the type of the numeric object.

Converting factory functions
function int (), long (), float (), and complex () are used to convert other numeric types to their corresponding numeric types. Starting with Python2.3, Python's standard data type adds a new member: a Boolean type. From this true and false now have constant values that are true and false (no longer 1 and 0)

Here are some examples of using built-in functions:

Copy Code code as follows:

>>> Int (4.25555)
4
>>> Long (42)
32k
>>> Float (4)
4.0
>>> Complex (4)
(4+0J)
>>>>>> Complex (2.4,-8)
(2.4-8j)
>>>
>>> Complex (2.3e-10, 45.3e4)
(2.3E-10+453000J)

function function
Python has five computational built-in functions for numeric operations: ABS (), coerce (), Divmod (), pow (), pow (), and round (). We'll take a look at 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 return math.sqrt (Num.real2 + num.imag2)

Coerce () returns only one tuple containing two numeric elements with type conversion completed

The Divmod () built-in function combines division and REST operations to return a tuple of both the quotient and the remainder. For an integer, its return value is the result of the floor removal and remainder operations. For floating-point numbers, the returned quotient portion is Math.floor (num1/num2), and the quotient portion is Ath.floor ((num1/num2). Real) for the plural.

Copy Code code as follows:

>>> 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 up floating-point numbers. It has an optional number of decimal places parameters. If you do not supply a decimal parameter, it returns the nearest integer (but still a floating-point type) that is closest to the first parameter. The second argument tells the round function to pinpoint the result to the specified number of digits after the decimal point.

Copy Code code as follows:

>>> Round (3)
3.0
>>> Round (3.154)
3.0
>>> round (3.499999, 1)
3.5

>>> Import Math
>>> for N in range (10):
Print round (Math.PI, N)

3.0
3.1
3.14
3.142
3.1416
3.14159
3.141593
3.1415927
3.14159265
3.141592654

numerical Operations built-in functions:

function function
ABS (num) returns the absolute value of num
Coerce (NUM1, num2) converts NUM1 and num2 to the same type and then returns as a tuple
Divmod (NUM1, num2) The combination of division-remainder operations. Returns a tuple (num1/num2,num1% num2). Rounds the quotient of floating-point numbers and complex numbers
Pow (NUM1, num2, mod=1) num1 to num2, if the MoD parameters are provided, then the results of the calculation of the MoD to take the remainder of the operation
Round (FLT, ndig=0) accepts a floating-point number flt and rounds it, saving ndig decimal places. If you do not supply the Ndig parameter, the default decimal point is 0 digits
Round () only for floating point numbers

applies only to built-in functions for integers:

function operations
Hex (num) Converts a number to a hexadecimal number and returns as a string
Oct (num) Converts a number to an octal number and returns as a string
Chr (num) converts the number of ASCII values to ASCII characters, which can range from 0 <= num <= 255
Ord (CHR) accepts an ASCII or Unicode character (a string of length 1) that returns the corresponding ASCII or Unicode value.
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

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.