05 numbers-Python core programming

Source: Internet
Author: User
Tags arithmetic operators bitwise bitwise operators integer division ord type casting

?? The introduction of the number?? Integral type?? The Boolean type?? The standard integral type?? Long integer type?? Floating-point real number?? Plural?? Operator?? Built-in functions?? Other number types?? Related Modules 5.1 Digital types      numbers provide scalar storage and direct access.     It is a non-changeable type, meaning that the value of the change number generates a new object.        python supports multiple numeric types: Integer, Long, Boolean, double, decimal, and complex. How to create a numeric object and use it to assign a value      (numeric object): Creating a numeric object is as simple as assigning a value to a variable         Anint = 1         along = -9999999999999999l        afloat = 3.1415926535897932384626433832795&nbs P       Acomplex = 1.23+4.56j How to update a numeric object      by assigning a value to a numeric object (re), you can "update" a numeric object.     Numeric objects are immutable objects, and you don't actually update the original values of the object, but instead generate a new numeric object and get a reference to it. How to delete a digital object      according to 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 (the variable name) unless you assign it a new value.     If you attempt to use an object reference that has already been deleted, an Nameerror exception is thrown. 5.2 int     Python There are several integer types.      Boolean type is an integral type with only two values.     Conventional integral types are integral types that are recognized by most modern systems.     python also has a long integer type. HoweverIt represents a value that is much larger than the long integer   of the C language. Boolean     Python supports Boolean types starting from version 2.3.     The value range for this type is only two values, which is the Boolean value True and the Boolean value false.      If you put a Boolean value in a numeric context (for example, add true to a number), true is treated as an integer value of 1, and false is treated as an integer value of 0. Standard integer types     Python's standard integer types are the most common numeric types.     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.     Python standard integer types are equivalent to the (signed) long integer type C.         integers are generally expressed in decimal, but Python also supports octal or hexadecimal notation for integers.         If the octal integer starts with the number "0", the hexadecimal integer begins with "0x" or "0X".          0101 84-237 0x80 017-680-0x92Long integers about python long integer types we have to mention that you should not confuse it with the long integer type of C or other compiled languages.    The typical value range for long integers of those languages is 32-bit or 64-bit.     Python's long integer type can express values only in relation to the (virtual) memory size supported by your machine, in other words, Python can easily express large, large, large integers.    A long integer type is a superset of a standard integer type, and a long integer type is useful when your program needs to use an integer larger than the standard integer type.    Add an L (uppercase or lowercase) after an integer value to indicate that the integer is a long integer. This integer can be in decimal, octal, or hexadecimal. 16384l-0x4e8l 017l-2147483648l 052144364L 299792458l 0xdecadedeadbeefbadfeeddeal-5432101234lCore style: long integers in uppercase letters "L"Although Python also supports long integers marked with lowercase l, it is strongly recommended that you use only uppercase "L", which effectively avoids the confusion of numbers 1 and lowercase L.    Python always uses uppercase "L" when displaying numeric values of long integer types.        Now that the integer and long integers are slowly being unified, you only have the opportunity to see "L" When you call the Repr () function on a long integer, and if you call the STR () function on a long integer object, you cannot see L. >>> along = 999999999l >>> along 999999999L >>> print along 999 999999 integral type and long integer type are silently and automatically converted to long integers if necessary. of course, those who want to call C can still continue to use both types of integers, because C code must distinguish between different integer types. >>> type (2) <type ' int ' > >>> type (2<<32) <type ' Long ' > >>> >>> 2<<32 8589934592l5.3 Double-precision floating-point number Python is similar to the double type in C, and is a dual-precision floating-point number that can be used directly    Decimal notation or scientific notation.    Each floating-point number occupies 8 bytes (64 bits), fully complies with the IEEE754 number specification (52M/11E/1S), where 52 bits are used to represent the base, 11 bits are used to represent the exponent, and 1 bits represent the symbol.     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, which indicates scientific notation). The positive (+) or negative (-) can be used between the E and the exponent to indicate the positive and negative of the exponent (a positive word can omit the symbol). 0.0-777. 1.6-5.555567119 96e3 * 1.0 4.3e25 9.384e-23-2.172818 Float (1.000000001) 3.1416 4.2e-10-90. 6.022e23-1.609e-195.4 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 part of the imaginary number. Imaginary numbers cannot exist alone, and they are always combined with a real part of a value of 0.0 to form a complex number. The plural is composed of real and imaginary parts. 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. 64.375+1j 4.23-8.5j 0.23-8.55j 1.23e-045+6.7e+089j 6.23+1.5j-1.23-875j 0+1j 9.80665-8.31441j-.0224+0jBuilt-in properties of complex numbers Table 5.1 plural properties Property DescriptionNum.real the real part of the complex number num.imag the imaginary part of the complex Num.conjugate () returns the complex's conjugate complex 5.5 operator numeric type to perform a number of operations. There are even specialized integer operators, from standard operators to numeric operators. The mixed-mode operator Python uses the method of numeric type casting to solve the problem of inconsistent numeric types. Numeric type conversionsStandard type operators     standard operators can be used for numeric types, operations between different data types, and Python internally converts two operands to the same data type before the operation. Arithmetic operators     monocular operator plus (+) and minus sign (-),     binocular operator, +,-,*,/,%, and **, //&nbsp, respectively, representing addition, subtraction, multiplication, division, remainder, Power and divide operations.      Division          programmers with a C background must be familiar with traditional division:            on integer operands , the floor is executed with the largest number of smaller than the quotient.                 For example 5 divided by 2 equals 2.5, where "2" is called the "floor" of the quotient, i.e. the result of "floor except".             performs a true division of floating-point operands.      Traditional Division          If integer division, traditional Division will remove the fractional part and return an integer (the floor is removed).         True division is performed if one of the operands is a floating-point number.             >>> $ perform integer result (floor) # flooring except      &NB Sp       0             >>> 1.0/2.0 # returns actual quotient# real except Law              0.5     Real Division        &NBSp The division operation always returns the real quotient, regardless of whether the operand is an integer or a floating-point number.             >>> returns real quotient         &NBS P   0.5             >>> 1.0/2.0 # returns real quotient   &nbsp ;         0.5     flooring except          Starting with Python 2.2, a new operator//has been added, To perform the floor except:  //Division, regardless of the numeric type of the operand, always removes the fractional part, returning the nearest number in the sequence of numbers that is smaller than the true quotient 。 >>> 1//2 # Floors result, returns integer # floor except, return integer 0 >>> 1.0//2.0 # Floors s result, returns float # floor except, return floating point 0.0 >>>-1//2 # Move left on number line# return than –0.5                   A small integer, that is, 1-1 to take the remainder of the integer is quite easy to understand, floating-point number to take more than slightly miscellaneous. The difference between the product of the largest integer that is less than or equal to the exact value.    namely: X-(Math.floor (x/y) * y) or for a complex number, the definition of the remainder is similar to floating-point numbers, except that the quotient takes only a few parts, namely: X-(Math.floor ((x/y). Real) * y).            The precedence relationship between the power operation operator and the unary operator is special: (??). The unary operator precedence of the exponentiation operator over its left-hand operand Low, the precedence of the unary operator over the right-hand operand High, because of this feature you will find two * * in the arithmetic operator table. NOTE: * * operator precedence is higher than single-mesh operator>>> 3 * * 2 9 >>> 3 * * 2 # * Priority higher than left-9 >>> (-3    * * 2 # Parentheses Increase-Priority 9 >>> 4.0 * *-1.0 # * * Priority lower than right-0.25 summary * bitwise operator (only for integers)    Python integers support standard bit operations: negation (~), bitwise-AND (&), or (|) and XOR (^) and left (<<) and right-shift (>>). Python handles bit operations like this:?? Negative numbers are treated as positive 2 complement. The left and right shift n bits are equal to the N power operations of 2 without overflow checking: 2**n.?? For long integers, the bitwise operator uses a modified 2-complement form to allow the symbol bits to extend infinitely to the left. the precedence of the inverse (~) operation is the same as the numeric single-digit operator, which is the highest priority in all bitwise operators.    The left and right shift operations take precedence, but are lower than the addition and subtraction operations.    With, or, the lowest precedence of the XOR operation.         5.6 Built-in functions and factory functions standard type function built-in function cmp () compare two number of sizes Str () converts a number to a string type () returns the type of a numeric object numeric type function conversion factory function built-in function        the function int (), long (), float (), complex (), and bool () are used to convert other numeric types to the corresponding numeric types. Starting with Python version 1.6, int () and long () accept a binary parameter when converting a string.     If it is a conversion between numeric types, the binary parameter cannot be used. The function Python has five arithmetic built-in functions for numerical operations: ABS (), coerce (), Divmod (), Pow (), and round (). ABS ()ABS () returns the absolute value of the given parameter.            If the argument is a complex number, it returns MATH.SQRT (Num.real2 + num.imag2).            >>> ABS ( -1) 1 >>> ABS (10.) 10.0 >>> ABS (1.2-2.1J) 2.41867732449 >>> abs (0.23-0.78) 0. 55 coerce ()            function coerce () provides programmers with a way to customize two numeric type conversions without relying on the Python interpreter.             function coerce () returns only one tuple that contains the two numeric elements for which the type conversion is complete.             >>> coerce (1, 2)              (1, 2) & nbsp;            >>>            >>> coerce (1 .3, 134L)             (1.3, 134.0)              &GT;&GT;&GT ;            >>> coerce (1, 134L)             (1L, 134L             >>>            >>> coerce (1j, 1 34L)             (1j, (134+0j))             >>>  & nbsp         >>> coerce (1.23-41j, 134L)         &NBSP   ((1.23-41j), (134+0j))          Divmod ()The Divmod () built-in function combines division and take-rest operations to return a tuple containing quotient and remainder.            For integers, the return value is the result of the floor addition and the fetch operation.            For floating-point numbers, the returned quotient portion is Math.floor (num1/num2).            For the plural, the quotient part is Math.floor ((num1/num2). Real). >>> Divmod (10,3) (3, 1) >>> Divmod (3,10) (0, 3) >>> Divmod (10,2.5) (4.0, 0.0) >>> Divmod (2.5,10) (0.0, 2.5) >>> Divmod (2+1j, 0.5-1j) (0j, (2+1j)) Pow ()Both the function pow () and the Double star (* *) operators can perform exponential operations.                The built-in function pow () also accepts the third optional parameter, a remainder parameter.                If you have this parameter, the POW () first carries out an exponential operation and then takes the result of the operation and the third parameter for the remainder operation. This feature is primarily used for cryptographic operations and is better than POW (x, y)% Z because the implementation of this function is similar to the C function pow (x, y, z). round ()The built-in function, round (), is used to round up floating-point numbers.                It has an optional number of decimal digits parameter.               If you do not provide a decimal parameter, it returns the integer closest to the first parameter (but still a floating-point type).            The decimal number parameter tells the round function to specify the number of digits after the decimal point.                The round () function is rounded by rounding the rules. That is, round (0.5) gets 1, round (-0.5) gets-1. Int (), round (), Math.floor ()?? the function int () truncates the fractional part directly. (The return value is an integer)?? The function floor () Gets the integer closest to the original number but less than the original number. (return value is floating point)?? The function round () gets the integer nearest to the original number.        (return value is floating-point number) numeric operations function built-in functions for integer-only function-conversion functions Python provides two built-in functions to return the 8-and 16-decimal integers represented by a string.        They are Oct () and Hex () respectively. They all accept an integer (arbitrarily-binary) object and return a string object of the corresponding value. Oct ()The OCT () accepts an integer (arbitrarily-entered) object and returns a string object with a 8-binary value. Oct ()Hex () takes an integer (arbitrarily-binary) object and returns a string object with a 16-binary corresponding value.        The ASCII conversion function built-in 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 ()The function Chr () accepts a single-byte integer value, returning a string whose value is the corresponding character. Ord ()            function ord () instead, it takes a character and returns its corresponding integer value.      Table 5.7 lists all the built-in functions for integer types   5.7 Other numeric types boolean "number"     boolean "True" and "false, " are subclasses of integral type, corresponding to 1 and 0 of integers.     Key Concepts of Boolean:       ?? There are two values that never change to True or false.         ?? A Boolean is a subclass of an integral type, but can no longer be inherited to produce its subclasses.         ?? The default value of an object without the __nonzero__ () method is True.         ?? For any number with zero value or empty set (empty list, empty tuple, empty dictionary, and so on), the Boolean value in Python is   false.         ?? In mathematical operations, the Boolean value of true and false corresponds to 1 and 0, respectively.         ?? Most standard library functions and built-in Boolean functions that previously returned integers now return a Boolean type.         ?? Both True and false are now not keywords, but will be in future versions of Python. Decimal floating point     decimal number is essentially a special   class for numerical calculations.     You can create decimal number floating-point numbers by string or other decimal number.     You must import the decimal module to use the decimal class.         >>> from decimal import Decimal5.8 related modules             Core modules: random      &NBsp     When your program requires random numbers, the random module can be useful.             This module contains multiple pseudo-random number generators, all with the current timestamp as a random number seed.             This allows you to start working as soon as you load this module.             most commonly used functions:                Two integer parameters, returning the random integer between the two Number                 Randrange () it takes the same parameters as the range () function, and returns the range ([Start,]stop[,step]) node randomly                 uniform () almost like Randint (), but it returns a floating-point number between the two (excluding the range cap).                 random () similar to uniform () only the lower limit is equal to 0.0, the upper limit constant equals 1.0      &NB Sp         choice () randomly returns an element of a given sequence                     &N Bsp          

05 Numbers-Python Core programming

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.