My Python introductory notes (3)

Chapter: Python basic grammar (lower)


Explicit is better than implicit. ——The Zen of Python


A variable

Understanding the variables in Python 1.1

  In Python, the variables in the strict sense should be called "name" can also be understood as a label. When the value assigned to a name (such as the "This is a Python" assigned to Python), Python is called variable.

1.2 variables defined and used

  In Python, do not need to declare variable names and types, direct assignment to create all types of variable, but a variable name is not arbitrary, you should follow a few rules:

  >> variable name must be a valid identifier

  >> variable name can not be used Python keywords

  >> caution lowercase l and uppercase letter O (confusingly)

  >> should choose meaningful words as variable names.

  Assign values ​​to variables can be accomplished by an equal sign (=), its syntax is:

Variable name = Value;

  For example, create an integer variable, and assign it a value of 220, you can use the following statement:

= 220 Number The   # Create a variable and assign a value of 220

  In addition, Python is a dynamically typed language, that is, the type of a variable can change at any time, for example, comes with Python IDLE, create a variable myname, and then assign it a value of variable output type is "Rain rainbow classmates", can see that the variable is a string type, then the variable assignment 1210, and outputs the amount of change of the type, the type can be seen that the variable is an integer. Examples are as follows:

 myname = "雨霓同学"
>>> print(type(myname))
<class 'str'>
>>> myname = 1210
>>> print(type(myname))
<class 'int'>

  In Python language, a built-in function type () can return type of the variable.

  In Python, allowing a plurality of variables point to the same value. For example: The two variables are assigned to 1210, and then were applied built-in function id () Get variable memory address to obtain the same result, for example:

>>> no = number = 1210
>>> id(no)
2284247074704
>>> id(number)
2284247074704

   In Python language, a built-in function id () can return the memory address of the variable referred to.

  Constants: Constants that the program is running, the value of the amount can not be changed, such as your ID number, pi in math, these are not going to change, in Python, it did not provide a definition of constant reserved word in PEP8 specification defines constants have capital letters and underscores, but in the actual project, the constants are assigned, other code can still be modified.

Second, the data type of the variable

  In Python, the data stored in the memory can have a variety of types. If a person's name can be used to store character and age can use numeric storage, whether married with Boolean type stores, these are the Python data types. Python3 data type contains six standard: Number The (digital), String (String), List (lists), Tuple (tuple), Sets (set), Dictionary (dictionary).

2.1 Digital Type (Number):

  Integer: integer value to an integer, i.e. there is no value of the fractional part. Integer types include decimal , binary , octal , hexadecimal number.

    Decimal: manifestation of a decimal integer are familiar with, such as the use of digital in our daily lives. As a decimal number can not begin with 0, (excluding 0).

    Binary number: only two base 1 and 0, the carry rule is "every a binary", such as 101 (that is, converted to decimal number 5)

    Octal: 0 ~ 7 composed carry rule is "every eight into a", and to start with a number of 0o, as 0o123 (converted to decimal number 83), Py3, the octal number must begin with 0o / 0O.

    Hex: a 0 ~ 9, A ~ F composition, carry rule "every a hexadecimal", and start 0x / 0X number, such as 0x25 (converted to decimal number 37), hex number system must begin with 0X or 0x.

  Floating point: floating-point number have integer and fractional parts, it is mainly used for decimal number comprising.

  Complex: exactly the same in the plural form complex with Python mathematics, there are a real part and an imaginary part, using j or J represents an imaginary unit.

  Boolean: Boolean type is mainly used to indicate a true or false value. In Python, the identifier (key) to be construed as True and False Boolean, Boolean value in Python additionally can be converted to a value, where True. 1 represents , False represents 0.

    Python boolean values ​​may be numerical calculation, it is not recommended to numerical values ​​of a Boolean operation, in addition Python, all objects may be true value of the test. The following cases are obtained which only is FALSE , or if other objects in the show while statements are true.

    >> False or None

    >> value of zero, including 0, 0.0, 0 imaginary number.

    >> empty sequence comprising a string, the null set, an empty list, empty dictionary.

    >> instance of the custom object, __bool__ the object returns False, or __len__ method returns 0.

2.2 Type String (String)

  Continuous string is character string in Python an immutable sequence, typically use single quotes " ''" double quotation marks "", "", or triple quotes off '' '' '' ' "or" "" " "" "" represents the three quotes on the semantic difference is not much, just some differences in form, single and double quote character must be on one line, and character sequences in a triple quotes can be distributed in a continuous multi row.

2.3 list (List), tuples (Tuple), set (Sets), dictionary (Dictionary)

  Lists and tuples can be used as an ordinary "array", which can hold the value of any number of any type, and these values are referred to as elements. Use the list of elements in square brackets [] contains the number of elements and values may be arbitrarily modified , and tuple element uses parentheses () comprising, an element can not be modified . Examples are as follows:

= LIST_NAME [1,2, ' Hello rain Ni students ' ] # This is a list of 
tuple_name = (1,2, ' Hello rain Ni students ' ) # This is a tuple 
a, b = type (list_name) , type (tuple_name) # view type 
Print (A, B)

 < class  ' List ' > < class  ' tuple ' >

  Set: a collection (set) is 0 or a combination of a plurality of disordered object reference, any element in the set are not repeated, for example:

= Set nullset >>> () # not without parameters, set creates an empty set 
>>> nullset 
set ()
 >>> of a_set = set ( ' abcdef ' ) # a str set as input to create a set will 
>>> of a_set 
{ ' E ' , ' A ' , ' C ' , ' D ' , ' B ' , ' F ' }

  Dictionary: A dictionary is a map data type in Python, the key - value pairs. Dictionary can store different types of elements, the elements using curly braces to contain. Examples are as follows:  

> Dice_name = { ' name ' : ' rain Ni students ' , ' Age ' : 22 is } # This is a dictionary
 >>> type (dice_name)
 < class  ' dict ' >

2.4 common data type conversion

  Python is dynamically typed languages ​​(also known as a weakly typed language, although type does not need to declare variables, but sometimes it is necessary to use type conversion) in Python, provides the following functions shown may be made between the various types of data change

  float (x):     x to type into a floating point
   complex (real, [, imag] ): creates a complex
   str (x):       will be converted to a string x

The In [. 1]: x = 3.1415926 # enter a floating point x 
the In [2]: X1 = int (x)     # x to the conversion to an integer   int (x): to convert x to an integer type 

the In [ . 3]: type (x1)   # view x1 numeric type 
Out [. 3 ]: int 

the in [ . 4]: x2 = a float (x1) will be converted to a floating x1 

the in [ . 5]: type (x2)   # view of numeric type x2 
Out [5 ]: a float 

the In [ . 6]: X3 = complex (220,284)   # generates a plurality of 

the In [ . 7 ]: X3 
Out [ . 7]: (220 + 284j ) 

the In [ . 8]: X4 = STR (x)   # x to be converted to string type 

the In [ . 9 ]: type (X4) 
Out [9]:str

  the repr () function will be explained for the object into the form of a read, i.e., converted to a string expression.

    Syntax: repr (object)

    Parameters: object-- objects

    Return Value: returns a string object format.

Name = >>> " Rain Ni students " 
>>> the repr (name)
 " 'Rain Ni students' " 
>>> dict = { ' name ' : ' rain Ni students ' , ' Age ' : ' 22 is ' }
 >> > the repr (dict)
 " { 'name': 'rain Ni students', 'Age': '22 is'} "

  eval () function is used to perform a string expression, and returns the value of the expression.

    Syntax: eval (expression [, globals [, locals]])

    Parameters: expression-- expression.

         Scope globals-- variables, global namespace, if provided, must be a dictionary object.

         Locals-- scope variables, local namespace, if provided, may be any map object.

    Returns: the result of an expression.

X = 220 >>> 
>>> the eval ( ' . 3 * X ' )   # calculation Python string expression and returns results 
660. 

>>> A = ' 284 '   # the eval method enables the quoted string itself removed , the original property of reserved characters 
>>> type (a)
 < class  ' STR ' > 
>>> B = the eval (a)
 >>> type (B)
 < class  ' int ' >

  chr (x):       with an integer as argument and returns an integer corresponding to the current ASCII code, where x can be a decimal number hexadecimal number may be numbers in the range of 0-1,114,111.

>>> a,b,c=chr(97),chr(8364),chr(0x30)
>>> a,b,c
('a', '', '0')

  ord (x):         a character x converted to its corresponding integer value which is a function CHR () function is matched to a string as an argument and returns the corresponding ASCII value, corresponding to the return value is a decimal integer.

>>> a,b=ord('a'),ord('')
>>> a,b
(97, 8364)

  int (x):    for a string or number into an integer,

       Syntax: int (x, base = 10) 

         Parameters: x-- string or a number, base-- hexadecimal number, the default decimal. (The first one is converted to digital, the second number is used to describe what a front hex)

# , Respectively the 12 conversion of 10 hex 16 hex, '0xa' conversion hexadecimal to decimal, octal conversion is 10 decimal, binary conversion is 10 decimal 
>>> a , B, C, D = int ( ' 12 is ' , 16), int ( ' 0xA ' , 16), int ( ' 10 ' ,. 8), int ( ' 10 ' , 2 )
 >>> A, B, C , D 
( 18 is, 10,. 8, 2)

  bin (x):         an integer x to a binary string

  oct (x):         an integer x to an octal string

  hex (x):        The integer x to a string of hexadecimal

# Respectively 220 decimal conversion in binary, octal converted to 284, converted to hexadecimal 1210 
>>> A, B, C = bin (220), OCT (284), hex (1210 )
 >>> A, B, C 
( ' 0b11011100 ' , ' 0o434 ' , ' 0x4ba ' )

   Note: During data type conversion, if the number string into a non-integer, an error is reported, following information:

>>> int('22岁')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '22岁'

Guess you like

Origin www.cnblogs.com/1210x1184/p/10970750.html