Python basic Syntax _ basic data type _ numerical explanation

Source: Internet
Author: User
Tags pow

Directory

    • Directory
    • Software Environment
    • Procedure for Python variable invocation
    • Numeric type
      • Delete a numeric type Object
      • boolean bool
      • Standard integer int
      • Long integer type
        • Double-precision Float float
        • Plural
    • Built-in function functions for numeric type objects
      • Absnumber to find the absolute value of number
      • Coercex y converts x y to the same numeric type
      • Divmodx y division-the combination of the take-rest operation
      • POW exponential operation or taking the result to the remainder
      • Rounding operation and precision of round floating-point type
      • Functions for integer objects only

Software Environment
    • System
      • CentOS 7
    • Software
      • Python 2.7.5
      • IPython 5.0.0
Procedure for Python variable invocation
In [441In [45]: anIntOut[451
    1. The reference value ID (anint) of the data object is obtained by the variable name Anint (that is, the index address of the data object in memory)
    2. Then get the value of the data object in memory by ID (anint) 1
    3. Finally, the value 1 of the variable anint is called out.

Note: Step 1. 2. It is transparent to the programmer.

Numeric type
    • Numeric type
      • boolean bool
      • Standard integral type Integral
      • Long Plastic
      • Float type float
      • Plural

Numeric data type, also known as a digital type. They apply to all types of operators (EG. Arithmetic/Shift/logic/...) And the built-in functions for handling numbers (EG. ABS ()/pow ()/round ()/divmod ()/...).
A numeric type is an immutable type , which means that changing the value of a numeric variable produces a new data object. Of course, this process is transparent to programmers, but understanding the principle of immutable types gives a deeper understanding of Python's assignment implementations.

immutable type: in Python, a variable is like a pointer. It points to the box containing the variable value (the data object) (the memory space occupied by the data object). For an immutable type object, we cannot change the contents of the box, but you can point the pointer to another box. Each time you assign a different number to a variable, you are actually creating a new data object and pointing the pointer back to the new data object.

Delete a numeric type Object

In Python, we can't really delete a numeric type object, but we can no longer use it. --Use the DEL statement to delete a reference to a numeric type object. After you delete a reference to a numeric object, we can no longer use the reference (the variable name) unless you assign it a new value, which triggers the nameerror.

The essence is: In Python, all types of data objects should have a corresponding reference (variable name), if the reference does not correspond to any data objects, the Python garbage collection mechanism will automatically recycle this reference. This invalidates a reference and saves memory space.

syntax : del variableName

boolean bool

The value range of a Boolean data object is only two values:True | False
The final result of any expression in Python that exists in a sentence (EG. If/while/elif) that has a judgment semantics can be represented by a Boolean value, which is determined by the _nonzero() function in the class.

The nonzero() function of the class is used to convert the class to a Boolean type (EG. BOOL (ClassName)). This is usually called when the class is judged and the class is converted to a Boolean type. For example, if A(): print ‘foo‘ the return value that is called in the statement is A().__nonzero__() judged. The following procedure should help you understand the role of nonzero():

class  a :  def  __nonzero__  :   #重载了 __ nonzero__ (self) function  print   ' a._nonzero__ () '  return  true   If  A ():  #隐式类型转换 bool (A ()), equivalent to A = a (); a.__nonzero__ (); return to True print   ' A is not zero '  else : print   ' A is zero '  print  bool (A ()) 

OUTPUT:

isnot zeroA._nonzero__()True
    • All expressions that exist in a sentence with a judgment semantics (eg. if/while/elif) will eventually implicitly perform the bool type conversion, eg. BOOL (expression result)

    • The essence of bool () is to call a function in the class to which the object belongs __nonzero__() , and, as long as the object's value is not NULL, then it is __nonzero__() == True false anyway.

That is, the final result of an expression is either true or false. Because of this, expressions are often used in statements that conform to the judgment semantics.

Note : When you create a Boolean type variable, capitalize the first letter.

Standard integer int

This is known as a standard integer because Python also has a long integer type.

number of digits occupied by the standard integer :
1. When using 32-bit compilers on 32 OS platforms, INT takes 32 bits and the value range is -2**31 ~ 2**31-1
2. Using a 64-bit compiler on a 64-bit OS platform, INT takes 64 bits and the value range is-2**63 ~ 2**63-1

a standard integer int is an immutable type :

In [91In [102

Note : num = 1; num = 2 Two statements do not refer to the same data object. Num in the first statement points to the value of data Object 1, at which point the reference of NUM is the index address where the data object is stored in memory, and Num in the second sentence represents the index address of the data object where value 2 is stored in memory.

In the above two assignment process, 1, 22 vlaue corresponding data objects in memory does not have any changes. Essentially only changes the reference to the variable num (the memory address pointed to). Therefore, the int type is an immutable type (because the data object has not changed). The value of the int type data object does not change in memory, but the reference to the variable can be changed.

Long integer type

Python's long integer is fundamentally different from the long integer type of a compiled language like C + +, because the value range of the Python long integer is not fixed, it is only related to the (virtual) memory size supported by your PC. in this way, Python can easily express a large integer type. However, in the present situation, the standard integer and the long integer type have the trend of merging.

Before Python 2.2, a standard integer data object would overflow error when it exceeded the range of values, and now if an overflow occurs, it is automatically captured by the Python parser and implicitly converts the standard integer to a long integer object.

A L|l numeric type object that identifies a long integer after an integer number.

In [3]: aLong = -999999999999999999999LIn [4]: type(aLong)Out[4]: long
Double-precision Float float

Double-precision floating-point type, or float type, similar to double float in C. Floating-point data type objects occupy 64-bit memory space, with decimal (.) and scientific notation (e) in two ways.

In [51]: floatTestOut[513.141592In [523.14159299999999999999999999999999999999999In [53]: floatTestOut[533.141593

The above example shows that the float type of data in Python also has a storage limit (8Byte).

Plural

Python also supports complex data types, a combination of a real number and an imaginary number to form a complex number. A complex number is a pair of ordered floating-point types (x, y) that is represented by the × + YJ, where x is the real part and Y is the imaginary part.
Note: Both the real and imaginary parts are floating point types.

In [483+6jIn [49]: pulralTestOut[49]: (3+6j)
Built-in function functions for numeric type objects

All of the functions described below are built-in function functions that can be used by numeric objects

ABS (number) to find the absolute value of number

ABS (...)
ABS (number), number
Return the absolute value of the argument.

ABS () returns the absolute value of the given parameter :

In [6]: abs(-1)Out[61In [7]: abs(10.)Out[710.0In [8]: abs(0.230.78)Out[80.55
Coerce (x, y) converts X, y to the same numeric type

Coerce (...)
Coerce (x, y) (x1, y1)
Return a tuple consisting of the numeric arguments converted to a common type, using the same rules as used by Arithme TIC operations. If coercion is not possible, raise TypeError.

convert x, y to the same numeric type :
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, both must be ordinary integers, without type conversions.

>>>Coerce (1.23-41j,134)((1.23-41j), (134+0j))>>>Coerce (1j,134L)(1j, (134+0j))>>>Coerce (1.3,134L)(1.3,134.0)>>>Coerce (1,134L)(1L,134L)>>>Coerce (1,2)(1,2)
Divmod (x, y) division-the combination of the take-rest operation

Divmod (...)
Divmod (x, y) (quotient, remainder)
Return the tuple ((x-x%y)/y, x%y). Invariant:div*y + mod = = x.

The Divmod () built-in function combines division and take-rest operations to return a tuple containing quotient and remainder ;
For an integral type, the Divmod () return value is the result of the floor addition and the fetch operation.
For floating-point types, the returned quotient portion is Math.floor (num1/num2)
For complex numbers, the returned quotient part is Ath.floor ((num1/num2). Real)

>>>Divmod (Ten,3)(3,1)>>>Divmod (3,Ten)(0,3)>>>Divmod (Ten,2.5)(4.0,0.0)>>>Divmod (2.5,Ten)(0.0,2.5)>>>Divmod (2+1j,0.5-1j)((-0+0j), (2+1j))

floor except// : Division No matter what numeric type the operand is, the resulting quotient will always shed the fractional part and take the value that is smaller and closest to the real quotient in the sequence of numbers.

>>>1//2  0  >>>1.0//2  0  >>>-1//2.0  -1  
POW () exponential operation, or taking the result to the remainder

Pow (...)
Pow (x, y[, z]), number
With the arguments, equivalent to X**y. With three arguments,
Equivalent to (x**y)% Z, and May is more efficient (e.g. for longs).

The Pow () built-in functions and ( ) operators are capable of exponential operation. But the POW () also attaches a take-up parameter to take the remainder: * *

EG. Pow (2,5,3) ==> 2 * * 5 3

and POW (2,5,3) is more efficient than pow (2,5)% 3. This feature is commonly used for cryptographic operations.

Round () Rounding operation and precision of floating-point type

Round (...)
Round (number[, ndigits]), floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This is always returns a floating point number. Precision may negative.

The Rouund () built-in function provides a non-breaking [, ndigits] parameter, and if this argument is not passed, the function returns the floating-point object closest to the number parameter. If this parameter is passed, a floating-point value that specifies the precision of the number parameter is returned:
Note: the Rount () built-in function is rounded by rounding (but the return value is still a floating-point object)

in [10 ]: round ( Span class= "Hljs-number" >3.45 ) out[10 ]: 3.0  in [11 ]: round (-3.5 ) Out[11 ]:-4.0  in [12 ]: round (-< Span class= "Hljs-number" >3.4 ) out[12 ]:-3.0  in [13 ]: round (3.499999999999 , 1 ) out[13 ]: 3.5  in [ Span class= "Hljs-number" >14 ]: round (3.499999999999 , 0 ) Out[14 ]: 3.0   

the difference between int ()/math.floor ()/round ():
1. Int (): Truncate the fractional part directly (returns an Integer object)
2. Floor (): an integer that is closest to the original but less than the original number (the return value is a floating-point object)
3. Round (): Gets the integer nearest to the original number (returns the floating-point object)

EXAMPLE:

in [ +]:ImportMathin [ -]: forEachnuminch(. 2,. 7,1.2,1.7, -. 2, -. 7, -1.2, -1.7):    ...:Print "Int (%.1f) \t%+.1f"% (eachnum,float (int (eachnum))) ...:Print "Floor (%.1f) \t%+.1f"% (Eachnum, Math.floor (Eachnum)) ...:Print "Round (%.1f) \t%+.1f"% (Eachnum, round (Eachnum)) ...:Print '-'* -...: Int (0.2)    +0.0Floor0.2)  +0.0Round0.2)  +0.0--------------------Int (0.7)    +0.0Floor0.7)  +0.0Round0.7)  +1.0--------------------Int (1.2)    +1.0Floor1.2)  +1.0Round1.2)  +1.0--------------------Int (1.7)    +1.0Floor1.7)  +1.0Round1.7)  +2.0--------------------Int (-0.2)   +0.0Floor (-0.2) -1.0Round (-0.2) -0.0--------------------Int (-0.7)   +0.0Floor (-0.7) -1.0Round (-0.7) -1.0--------------------Int (-1.2)   -1.0Floor (-1.2) -2.0Round (-1.2) -1.0--------------------Int (-1.7)   -1.0Floor (-1.7) -2.0Round (-1.7) -2.0--------------------
Functions for integer objects only

Binary conversion function
Octal: Oct ()
Hex: Hex ()

ASCII conversion function
Chr (): Receives an integer value that returns a character corresponding to its value.

In [22]: chr(97)Out[22‘a‘

Ord (): Receives a character that returns its corresponding integer value.

In [23]: ord(‘a‘)Out[2397

Python basic Syntax _ basic data type _ numerical explanation

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.