码迷,mamicode.com
首页 > 编程语言 > 详细

python3----运算符

时间:2018-01-15 20:37:17      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:进制   整数   support   blog   2.3   body   traceback   rand   false   

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

           

>>> 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表示符号为:&、|、^、~

例子如下:

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

 

python3----运算符

标签:进制   整数   support   blog   2.3   body   traceback   rand   false   

原文地址:https://www.cnblogs.com/jonm/p/8289268.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!