Python foundation (2) --- data types



1. Differences between PYTHON versions:

    2.x and 3.x versions compared

version

    2.x

    3.x

   print

    print " " or print() can print normally

     , only print() can print in this form, otherwise SyntaxError will appear 

    input raw_inut 

     input: output the native data type, what type of value is input, output what type raw_input: all output in string form 

     3.x canceled the raw_input method, only use input() method to prompt for input string , This method and the 2.x version of raw_input() If you want to implement the value of the native data type output with 2.x input(), you can use eval(input()) 

   class

    2.x supports new-style classes, and classic classes, When using new-style classes, the class inheritance order will affect the final result of inheritance.

    New-style classes must be used to solve the problem of inheritance order between classes

   /

    Example: 1/2, the value of 2.x output is 0

    For example: 1/2 3.x output The value is 0.5

    

2. PYTHON data type

  int integer, such as 1,123,1234,-1,-123..., the range is between -2**31~2**31-1, depending on the operating system, it will not be smaller than this range.

  float Floating point, such as 1.1, 1.12, -1.1, -1.12...

  str String, such as 'hello', '123', 'abc'... Strings need to be enclosed in single or double quotes.

  bool Boolean type, only two values, true: True, false: False, any non-zero data type, the result is true, when the result is 0, it is False.

  This type of long exists only in version 2.x, and the range of values ​​is infinite, depending on the available virtual memory.

  complex Complex numbers, such as 3.12j, 2.45e-6j...

  tuple such as ('1','abc','hello').

  List such as ['a','abc',' PYTHON '].

  Dictionary (dict) such as {'name':'tom', 'age':'20', 'job':'IT'}.

3. PYTHON encoding

   PYTHON 2.x version default string character encoding, 1 character can only store 8 bits, you can use the built-in functions, chr() and ord() for character conversion.

   PYTHON 3. The x version uses the unicode encoding format by default, and the built-in functions unichr() and ord() can be used for character conversion.

4. PYTHON Naming specification

   PYTHON variable names (identifiers) can only start with a letter or underscore, and cannot contain special characters. Note that PYTHON reserved keywords cannot be used as variable names, which is equivalent to rewriting PYTHON 's built-in methods, which may affect the calls of other methods , specific PYTHON reserved words, see section 4.1.

  In order to write the specification, it is recommended to use a uniform style for variable names, for example: camel case is TestLoginSucess or test_login_success.

  An identifier that begins with a single leading underscore means the convention is private.

  Identifiers beginning with two leading underscores indicate strongly private identifiers.

  If the identifier is terminated by two underscores, the identifier is a language-specific name.

  In addition, it should be noted that PYTHON is dynamic in advance, that is to say, it is not necessary to specify the data type of the variable when defining the variable. PYTHON will automatically change the data type of the variable when a variable is assigned.

4.1 PYTHON reserved words #By



  

   importing the keyword module, we can check which keywords are currently reserved by PYTHON

import keyword


#View PYTHON reserved keywords

keyword.kwlist


#2.x输出['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']


#3.x输出['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with' , 'yield'] #Note   View CodeFalse, it means that the variable is not a system reserved keyword, you can usekeyword.iskeyword('name') #Return# If you are not sure whether the variable name is a keyword, you can also use the following method to check whether it is a key WordView CodeFalse, it means that the variable is not a system reserved keyword, you can usekeyword.iskeyword('name') #Return# If you are not sure whether the variable name is a keyword, you can also use the following method to check whether it is a key WordView Code #Return False, it means that the variable is not a system reserved keyword, you can use keyword.iskeyword('name') . #If you are not sure whether the variable name is a keyword, you can also use the following method to check whether it is a keyword


, 3.x added ['False','None','True','nonlocal'] and removed the keywords of 2.x ['exec'], everyone is in the naming convention When it is time, it should follow the keywords of 3.x, which is convenient for backward compatibility









  



 

 

5. PYTHON comment

   PYTHON has two comment methods, one is a single-line comment, add a # symbol before the statement, or you can use a multi-line comment, use three consecutive single quotes to add on both sides of the content range that needs to be commented, or you can Use three consecutive double quotes.

Example:

   '''

    Single quote comment

   '''

 

   """

    Double quote comment

   """

 

6. PYTHON 's syntax

   PYTHON is famous for its simplicity, abandoning other {} curly braces such as c, and In the future, the readability of the language is pursued, and syntax indentation is mandatory. The code indentation of the same statement block must be the same. It is responsible for the indentation error IndentationError. If you want to write multiple statements in one line, you can use them to separate them

 

. 7. PYTHON Operators

   7.1 Arithmetic Operators



   Arithmetic Operators

  

  Operator

    Description

    Example

   +

    Addition

    

     

      >>> 14 - 59

      

   -

    Subtraction

    

     

      >>> 14 - 5

9

      

    *

     multiplication

     

     

      >>> 5 * 14

70

      

    /

    division

     

     

      >>> 14 / 5

2.8

      

    %

     modulo, that is, the remainder of the quotient of the two

     

     

      >> ;> 14 % 5

4

      

    **

     exponentiation

     

     

      >>> 2 ** 3

8

      

    //

     Integer division, returns the integer part of the quotient of two numbers

    

     

      >>> 10 // 3

3

      

    

  7.2 Comparison operator : Comparison



   operators are not limited to numbers, strings, lists, etc. can be compared

  

  . Operator

    Description

    Example

   ==

    Determine whether two objects are equal (equal returns True, unequal returns False)

    

     

      >>> ' abc' == 'abc'

True

      

   !=

    Determines whether two objects are not equal (contrary to ==, equal returns False, not equal returns True)

    

     

      >>> 1 != 2

True

      

   <>

    Determines whether two objects are not equal (same as above, but Not recommended)

     

   >

    Judge whether the first object is greater than the second object, return True if greater than, return Fasle if not greater than (including equal)

    

     

      > > > 3 > 1

True

      

   <

    Judge whether the first object is less than the second If less than or equal to, return True, not less than (including equal) return Fasle

    

     

      >>> 3 < 4

True

      

   >=

    Determine whether the first object is greater than or equal to the second object, return True if greater than or equal, otherwise return False

    

     

      >>> 3 >= 3

True

      

   <=

    Determine whether the first object is less than or equal to the second object, return True if less than or equal, otherwise return False

    

     

      >>> 3 <= 4

True

      

     7. 3 Assignment Operators: Assignment Operators



   Assignment

  

  Operators

    Description

    example

   =

    assignment

    a = c 

   +=

    self-incrementing assignment a += 1 is equivalent to a = a + 1

    a += 1

   -=

    self-decrementing assignment a -= 1 is equivalent to a = a - 1

    a -= 1

   * =

    Multiplication assignment a *= 1 is equivalent to a = a * 1

    a *= 1

   /=

    Self division assignment a /= 1 is equivalent to a = a / 1

    a /= 1

   %=

    Modulo assignment a %= 1 is equivalent to a = a % 1

    a %= 1

   **=

    exponentiation assignment a **= 1 is equivalent to a = a ** 1

    a**= 1

    //=

    self-dividing assignment a //= 1 Equivalent to a = a // 1

    a //= 1

    

  7.4 Bitwise Operators: Logical Calculations in Binary Bits     Bitwise



   Operator

  

  Description     Example





   &

    bitwise AND

    

     

      >>> 5 & 14

4

      

   |

    bitwise OR

    

     

      >>> 5 | 14

15

      

   ^

    XOR

    

     

      >>> 5^14

11

      

   <<

    shift left

    

     

      > ;>> 14 << 2

56

      

   >>

    Shift right

    

     

      >>> 14 >> 2

3

      

   8. PYTHON data type manipulation

  8.1

  Variables It is necessary to temporarily save the identifier of the data that can be changed continuously. PYTHON has its own memory recycling mechanism, so there is no need to consider the destruction of variables in the development process.

   The difference between PYTHON and other static languages ​​such as C is that PYTHON When the variable is assigned, the interpreter now creates the data object in memory, then creates the variable, and points the variable to the previously created data object. It's a bit like a pointer in the C language, so some people say that although PYTHON has no concept of    a pointer, everything is

  a pointer , which is equivalent to pointing the memory space 3 pointed to by a to b at the same time. At this time, b is also equal to 3 a = 5 #Assign the value of 5 to the a variable. At this time, since the previous a has been assigned a value, the PYTHON interpreter will a The memory space pointed to is changed to point to 5 print(a,b) (5,2) #At this time, the print output is 5,2, because although b=a, and the value of a has been changed, b=a only changes the b points to the memory address pointed to by a. It does not mean that the value of a and a changes in the true sense. It only changes the memory address pointed to by a. When multiple variables point to the same address space, PYTHON 's own memory recycling mechanism, A mark will be made in this memory space, how many people have referenced this memory space, just + how many 1s, until the reference is 0, at this time the PYTHON interpreter will take back the memory space, which is also different from other One of the biggest features of development languages ​​is that you don't need to pay attention to memory recycling.   View Code #When    you want to check whether the current two variables point to the same memory address, you can use the id() method a = 2 print(id(a)) #Print result is 140723441682448



  














  



 



  










b = a

print(id(b))

#The print result is 140723441682448 #Visible

, both a and b point to the same address space, Note: The above two values ​​are related to the platform used, not necessarily the same value, But these two values ​​must be equal


a = 5

print(id(a)) #The print


result is 140723441682376


print(id(b))

#The print result is 140723441682448 #By

observing the pointer changes of the two variables, it can be found that a The change of the value does not affect the b

  

  View Code that has been assigned

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326388671&siteId=291194637