【Python 3.6.1】基本计算
1、加减乘除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[root@dt ~]# python3 Python 3.6.1 (default, Jul 2 2017, 16:09:42) [GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> 1+2 3 >>> 1-2 -1 >>> 5*8 40 >>> 1/2 0.5 >>> |
此处要简单说一下,python3和python2在这里有点儿区别,如果是python2的话,那么1/2=0,原因是python2取了整,测试如下:
1 2 3 4 5 6 7 8 |
[root@dt ~]# python Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> 1/2 0 >>> |
那么python2想得到0.5怎么办?可以使用浮点数,如下:
1 2 3 4 5 6 7 |
[root@dt ~]# python Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 1.0/2.0 0.5 >>> |
python3使用浮点数相除,得到的结果与python2.0相同
2、取余
1 2 3 4 5 6 7 8 9 10 11 12 13 |
[root@dt ~]# python3 Python 3.6.1 (default, Jul 2 2017, 16:09:42) [GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> 1%2 1 >>> 2%2 0 >>> 3%2 1 >>> 4%2 0 >>> |
3、幂运算
1 2 3 4 5 6 7 8 9 10 11 |
[root@dt ~]# python3 Python 3.6.1 (default, Jul 2 2017, 16:09:42) [GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> 2**3 8 >>> -3**2 -9 >>> (-3)**2 9 >>> |
注:-3**2 等同于 -(3**2)