python2和python3的区别

python2 与 python3的区别:

__ future __ 模块:

python3介绍的一些python2不兼容的关键字和特性可以通过在Python2的内置__future__模块导入,如果在python2中支持python3的代码,可以导入__future__模块。

print函数:

  • print语法大家都比较熟悉在python2中声明已经被python3中的print()函数所取代了。在python3中如果使用print将会报错(SyntaxError)。

python2:

print 'python',python_version()
print 'hello world'
print 'name is',;print 'gallo'
#result:
#python 2.7.6
#hello world
#name is gallo

python3:

print('python',python_version())
print('hello world')
print("name is",end="")
print("gallo")

#reslut:
#python 3.7.1
#hello world
#name is gallo

整除

python3的版本变化中,整数计算可以说是很大的并且可能在移植过程中造成很大的危险。

  • 在python2中整除类似于C语言中的整除

python2

>>> 3/2
>>> 3//2
>>> 3/2.0
>>> 3//2.0

#result
# 1
# 1
# 1.5
# 1.0

python3

>>> 3/2
>>> 3//2
>>> 3/2.0
>>> 3//2.0

# reslut
# 1.5
#  1
# 1.5
# 1.0

Unicode

python 2中ASCLL 是字符串类型,Unicode()是单独的,不是byte类型
现在,在python3有了Unicode(utf-8)字符串,以及一个字节类:byte和bytearrays类型。
由于Python3源码文件默认使用utf-8编码,使得变量名为汉字合法。

>>>梅西 = ‘Messi’
>>>print(梅西)
Messi

python2

>>>str = '梅西'
>>>str
'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c'

python3

>>> str = "我喜欢踢足球"
>>> str
'我喜欢踢足球'

异常

在python 3中异常做的轻微的改变,使用as作为关键词。

将捕获异常的方法从 except exc,var 改为 except exc as var.

不等运算符

Python 2中不等于有两种写法 !=和<>
python 3中去掉了<>,只有!=一种写法

去掉了repr表达式``

python 2中反引号 `` 相当于repr函数的作用.
python 3只允许使用repr函数.
**repr()**将对象转化为供解释器读取的形式。

比较不可排序类型

在python3中当不可排序类型作比较的时候,会抛出一个类型错误。

python 2

>>> [1,2] > 'foo'
>>>(1,2) > 'foo'
>>>[1,2] > (1,2)

#result
#False
#True
#False

python 3

[1,2] > 'foo'
(1,2)>'foo'
[1,2]>(1,2)

#将会报错 :不同数据类型之间不能进行比较

next() 函数 and .next()方法

python2方法与函数都可以使用,在python3中使用.next()方法会抛出异常。

input ()和 raw_input()

在python3中input的类型都为字符串类型,但是在python2中如果输入123将默认为int类型,如果要保证输入的为字符串类型应该使用的是raw_input()

python 2

>>> my_input = input('enter a number:')
enter a number: 123
>>> type(my_input)
<type 'int'>

>>> my_input = raw_input('enter a number:')
enter a number: 123
>>> type(my_input)
<type 'str'>

python3

#只有input()函数
my_input = input('enter a number')
enter a number: 123
type(my_input)
<type 'str'>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章