• (Python )运算符


    这一节,将学习运算符,主要是算术运算符和逻辑运算符


    1.算术运算符


    • 除法运算,整数/整数=整数,浮点数/整数=浮点数,整数/浮点数=浮点数:

    >>> 17/3
    5
    >>> 17/3.0
    5.666666666666667
    >>> 17.0/3
    5.666666666666667
    >>>

    • 乘法运算,整数*整数=整数,浮点数*整数=浮点数:

    >>> 17*10
    170
    >>> 17.0*10
    170.0
    >>> 17.00*10
    170.0
    >>> 12.3*0.3
    3.69

    • 加法运算,整数+整数=整数,整数+浮点数=浮点数

    >>> 1+2
    3
    >>> 1.0+2
    3.0
    >>> 1.0+2.0
    3.0

    注意:有时候,加法运算的值可能有一定的误差,例如:1+1.22并不等于2.22

    >>> 1.22+1
    2.2199999999999998
    >>> 1.23+1
    2.23

    • 减法运算,整数-整数=整数,整数-浮点数=浮点数,浮点数-整数=浮点数:

    >>> 10-2
    8
    >>> 10.0-2
    8.0
    >>> 10-2.0
    8.0

    注意:有时候,减法运算的值可能有一点误差,例如:1.22-0.1并不等于1.12

    >>> 1.22-0.1
    1.1199999999999999
    >>> 1.23-0.1
    1.13

    •  Python的%是求模运算符(整数%整数=余数):

    >>> 5%2
    1
    >>> 5.4%2
    1.4000000000000004
    >>> 5%0.2
    0.19999999999999973

    • 求幂运算符:**

    >>> 10**2
    100
    >>> 10**2.0
    100.0

    • 取整除运算符为//, 返回商的整数部分:

    >>> 10//2
    5
    >>> 10//3
    3
    >>> 10.0//3
    3.0

     


    2.逻辑运算符


    •  逻辑运算符与、或、非,对应的Python符号为:and 、or、not

    123624995

     

     

     

     

     

    >>> False and True
    False
    >>> True and True
    True
    >>> False and False
    False
    >>> False or True
    True
    >>> True or True
    True
    >>> False or False
    False

    >>> not True
    False
    >>> not False
    True

     

    • 移位运算符<<和>>,表示将数的二进制比特位向左或向右移动几位:

    >>> 4<<2
    16
    >>> 4>>2
    1
    >>> 4>>3
    0
    >>>
    >>> 4>>4
    0
    >>> 4<<32
    17179869184L
    >>> 4<<64

    注:向右无限移位可以将数移位为0,向左移位可以使数无限增大。 移位运算符两端的数必须为整数,否则会报错

    >>> 0.2>>2

    Traceback (most recent call last):
    File "<pyshell#53>", line 1, in <module>
    0.2>>2
    TypeError: unsupported operand type(s) for >>: 'float' and 'int'
    >>> 2>>0.1

    Traceback (most recent call last):
    File "<pyshell#54>", line 1, in <module>
    2>>0.1
    TypeError: unsupported operand type(s) for >>: 'int' and 'float'

    •  按位与、按位或、按位异或、按位翻转,对应的Python表示符号为:&、|、^、~

    1
    例子如下:

    >>> 8&10
    8
    >>> 8|10
    10
    >>> 10^8
    2
    >>> ~10
    -11
    >>> ~-12
    11

  • 相关阅读:
    ★★★
    ★★
    小狼程序员:工作遐想
    广联达BB了
    计算机网络简单理解
    做个合格的(优秀的)测试开发人员
    开发、测试、测试开发
    8.21
    C++ 选择题总结(回调函数 || 类方法(实例方法)|| )
    深拷贝实现笔记
  • 原文地址:https://www.cnblogs.com/Lival/p/4390989.html
Copyright © 2020-2023  润新知