Python第一天:python2.x和python3.x的区别

查看Python版本

# python -V

Python2.7.5是centos7中默认安装的Python

[root@localhost ~]# python -V
Python 2.7.5
[root@localhost ~]# python
Python 2.7.5 (default, Oct 30 2018, 23:45:53) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> #输入exit()或者ctrl+d退出Python的交互式编程模式

 查看Python在Linux中的安装位置

# whereis python

[root@localhost ~]# whereis python
python: /usr/bin/python2.7 /usr/bin/python /usr/lib/python2.7 /usr/lib64/python2.7 /etc/python /usr/include/python2.7 /usr/share/man/man1/python.1.gz
[root@localhost ~]# 

 升级Python2.x到Python3.x请参照另一篇博客

https://www.cnblogs.com/djlsunshine/p/10689591.html

编写第一个Python实例“hello Word”

# vi hello.py

[root@localhost ~]# vi hello.py 
#!/usr/bin/python 
print("Hello, World!");

 使用Python命令执行该脚本文件

# python hello.py

[root@localhost ~]# python hello.py 
Hello, World!

除法运算

Python中的除法有两个运算符

“/”和“//” 

在Python2.x中,整数相除的结果是一个整数,把小数部分完全忽略掉

浮点数除法会保留小数点的部分得到一个浮点数的结果

[root@localhost ~]# python2 
Python 2.7.5 (default, Nov 20 2015, 02:00:19) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 / 2
0
>>> 1.0 / 2.0
0.5
>>> 

在Python3.x中,“/”除法不再这么做了,对于整数之间的相除,结果也会是浮点数

[root@localhost ~]# python3
Python 3.6.3 (default, Apr 12 2019, 00:16:06) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1/2
0.5
>>> 

“//”除法叫做floor除法,会对除法的结果自动进行一个floor操作,在python2.x和python3.x中是一致的。

python2:
>>> -1 // 2  
-1
>>> 
python3:
>>> -1 // 2  
-1
>>> 

注意:并不是舍弃小数部分,而是执行floor操作,如果要截取小数部分,那么需要使用math模块的trunc函数

python3:
>>> import math
>>> math.trunc(1/2) 
0
>>> math.trunc(-1/2)           
0
>>> 

end

原文地址:https://www.cnblogs.com/djlsunshine/p/10690514.html