The Road to Python, Part 2: Introduction and Basics of Python 2

1. Compound assignment operator

               +=   、 -=  、 *=  、 /=  、 //=  、 %=  , **=

             x + = y etc. x = x + y

            x-= y etc. x = x --y

            。。。。。。

           Requirement: The variable must exist when the operation is performed

>>> x = 3
>>> x += 1
>>> x
4
>>> x -= 1
>>> x
3
>>> x *= 2
>>> x
6
>>> x /= 3
>>> x
2.0
>>> x **= 3
>>> x
8.0
>>> x //= 3
>>> x
2.0
>>> x *= 5
>>> x
10.0
>>> x %= 3
>>> x
1.0
>>>

 2, relational operators

          < , <= , > , >= , == , ! = ("<>" is only available for python2)

         Description: Relational operators return a value of type Boolean (True or False); None is False compared to any object.

>>> x = 10
>>> x > 8
True
>>> x < 8
False
>>> x >= 8
True
>>> x <= 8
False
>>> x == 8
False
>>> x != 8
True
>>> x=9
>>> x==None
False
>>> 80 > x >60
False

 3, the function that generates the object

             float(obj) is used to convert a string or a number to a floating point number; if the parameter cannot be output, it returns 0.0;

             int(int [, base = 10]) is used to convert a string or a number to an integer, and returns 0 if no arguments are given;

             bool(x) generates a bool value from x (True or False)

             complex(r = 0.0 , i = 0.0) generates a complex number with numbers (real part r, imaginary part i);

             str(obj=" ") converts an object to a string

            

>>> x = "3.1"
>>> type(x)
<class 'str'>
>>> float(x)
3.1
>>> type(float(x))
<class 'float'>
>>> int()
0
>>> x = 0.0
>>> int(x)
0
>>> x = int("1101")
>>> x
1101
>>> x = int("1101",2) #2代表二进制
>>> x
13
>>> x = int("1101",8) #8代表八进制
>>> x
577
>>> x = int("1A", 16)
>>> x
26
>>> help(int) #base=10 十进制
Help on class int in module builtins:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 | 
>>> complex(1,2)
(1+2j)
>>>complex()
0j
>>>
>>> bool(0)
False
>>> bool(0.0)
False
>>> bool(0.0001)
True
>>>
>>> bool(0j)
False

         Cases where the bool() function returns false:

               False logical false value, None empty value, 0 , 0.0 , 0j all zero values, " " empty string, [] empty list, () empty tuple, { } empty dictionary, set( ) empty set;

    4. Preset data type functions

                abs(x) takes the absolute value of x;

              

 

Guess you like

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