Python2和Python3常用知識的區別

疫情當前,也不能正常上班,在家很是焦慮,就想着剛點啥,正好收到組長通知,以後不用Python2.7,改用Python3了,於是就開始複習它倆區別的旅途~

其實Python提供了__future__模塊,把下一個新版本的新功能,導入到當前(舊版本)中

舉個簡單的栗子~
Python2.7導入Python3的功能

>>>print('hello','world')
('hello','world')
#上面是沒有導入future模塊輸出的結果,下面是導入後的結果
>>>from __future__ import print_function
>>>print('hello','world')
hello world

這樣新版本的特性便可以和舊版本兼容。
還有一些其他特性庫,如精確除法:
(哈哈,時間比較多就再舉個簡單的栗子吧^^~)

>>>3/4
0
#上面是沒有導入future模塊輸出的結果,下面是導入後的結果
>>>from __future__ import division
>>>3/4
0.75

(嘿嘿,不止我寫的兩個庫,還有很多庫,就需要大家自己去查找了,在此就不一一列舉了^^~)

是不是看了半天還沒有看到他們具體區別在哪裏,開始有些着急了,啊哈,這就來了,年輕人要有耐心^^~

Python2.7和Python3區別

1.print函數

Python2.7

>>> print ‘ok’
ok

Python3

>>> print(‘ok’)
ok

啦啦啦,這個大家是不是覺得是小意思呀~ 那我在這裏就不總結了哈^^~

2.整數除法

Python2.7

>>> 5/2
2

Python3

>>> 5/2
2.5
>>> 5//2
2
總結:

Python2.7除法結果取整,Python3 ‘ / ’ 結果精確到小數點後,若想和Python2.7結果一樣,可以使用 ‘ // ’ 便可以取整了~

3.編碼

Python2.7

>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> c = '你好'.decode('gbk')
>>> c
u'\u4f60\u597d'
>>> c = '你好'
>>> c
'\xc4\xe3\xba\xc3'
擴展:
>>> type(u"ass")
<type 'unicode'>
>>> type("ass".decode('utf8'))
<type 'unicode'>
#兩者返回類型都是unicode類型

Python3

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> 哈哈 = 'hello'
>>> print(哈哈)
hello
>>> 哈哈
'china'
>>> n ='你好'
>>> n
'你好'
擴展:
>>> type(u'asd')
<class 'str'>
>>> type("asd".decode('utf8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'
#報錯,Python3不允許這樣寫,並且Python3特有的byte類型
>>> type(b'a')
<class 'bytes'>
>>> type(b'12')
<class 'bytes'>
總結:

Python2.7默認編碼是ascii,文件頂部需寫# coding=utf-8
Python3默認編碼utf-8,所以文件頂部不需要些 # coding=utf-8

4.xrange,range

Python2.7

>>> range(5)
[0, 1, 2, 3, 4]
>>> xrange(5)
xrange(5)

Python3

>>> range(3)
range(0, 3)
>>> li = list(range(3))
>>> li
[0, 1, 2]
總結:

Python2.7 range生成list,xrange是生成器,Python3 統一用range,想輸出列表,需要使用list() 哦~

5.處理異常

Python2.7

try:
	pass
except Exception, e:
	raise e

Python3

try:
	pass
except Exception as e:
	raise e
總結:

Python2.7可以不寫as,Python3必須寫as 呢~

6.map

Python2.7

>>> def Num(a,b):return(a,b)
...
>>> L1 = [1,2,3,4,5,6,7]
>>> L2 =  [ 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven' ]
>>> map(Num,L1,L2)
[(1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four'), (5, 'Five'), (6, 'Six'), (7, 'Seven')]

Python3

>>> def Num(a,b):return(a,b)
...
>>> L1 = [1,2,3,4,5,6,7]
>>> L2 =  [ 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven' ]
>>> map(Num,L1,L2)
<map object at 0x000001F4AB1B4390>
>>> list(map(Num,L1,L2))
[(1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four'), (5, 'Five'), (6, 'Six'), (7, 'Seven')]
總結:

Python2.7 返回list,Python3 若想返回list,需使用list() 哦~

7.cmp(),operator

Python2.7

>>> cmp(1.1,2)
-1
>>> cmp(3,1)
1
>>> cmp(4,4)
0

Python3

>>> import operator
>>> operator.gt(2,1)
True
>>> operator.ge(2,5)
False
>>> operator.eq(2,2)
True
>>> operator.le('2dgfh','aa')
True
>>> operator.lt('asd','fh')
True
>>> operator.ne('asd','fh')
True
總結:

Python2.7 cmp(x,y)函數,x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1;
Python3取消cmp()函數,添加了新模塊operator,返回布爾值
operator.gt(x,y) #greater than(大於)
operator.ge(x,y) #greater and equal(大於等於)
operator.eq(x,y) #equals(等於)
operator.le(x,y) #less and equal(小於等於)
operator.lt(x,y) #less than (小於)
operator.ne(x,y) #not equals(不等於)

8.raw_input, input

Python2.7

>>> name = raw_input('姓名:')
姓名:哈哈
#輸入中文名字
>>> name
'\xb9\xfe\xb9\xfe'
>>> type(name)
<class 'str'>

>>> name = raw_input('姓名:')
姓名:hhh
#輸入字母名字
>>> name
'hhh'
>>> type(name)
<class 'str'>

>>> age = raw_input('年齡:')
年齡:12
>>> age
'12'
>>> type(age)
<class 'str'>

Python3

>>> name = input('姓名:')
姓名:哈哈
>>> name
'哈哈'
>>> type(name)
<class 'str'>

>>> name = input('姓名:')
姓名:hh
>>> name
'hh'
>>> type(name)
<class 'str'>

>>> age = input('年齡:')
年齡:13
>>> age
'13'
>>> type(age)
<class 'str'>

9.iteritems

Python2.7

>>> info = {'name':'xiaohong','age':'12','gender':'girl','score':'98'}
>>> info
{'gender': 'girl', 'age': '12', 'score': '98', 'name': 'xiaohong'}
>>> b=info.iteritems()
>>> b
<dictionary-itemiterator object at 0x000000000320C188>
>>> list(b)
[('gender', 'girl'), ('age', '12'), ('score', '98'), ('name', 'xiaohong')]
>>>
>>> info = {'姓名':'小紅','年齡':'12','性別':'女','成績':'98'}
>>> info
{'\xb3\xc9\xbc\xa8': '98', '\xc4\xea\xc1\xe4': '12', '\xd0\xd5\xc3\xfb': '\xd0\xa1\xba\xec', '\xd0\xd4\xb1\xf0': '\xc5\xae'}
>>> a = info.iteritems()
>>> a
<dictionary-itemiterator object at 0x000000000320C458>
>>> list(a)
[('\xb3\xc9\xbc\xa8', '98'), ('\xc4\xea\xc1\xe4', '12'), ('\xd0\xd5\xc3\xfb', '\xd0\xa1\xba\xec'), ('\xd0\xd4\xb1\xf0', '\xc5\xae')]

Python3

>>> info = {'姓名':'小紅','年齡':'12','性別':'女','成績':'98'}
>>> info
{'成績': '98', '姓名': '小紅', '年齡': '12', '性別': '女'}
>>> c = info.items()
>>> c
dict_items([('成績', '98'), ('姓名', '小紅'), ('年齡', '12'), ('性別', '女')])
>>> type(c)
<class 'dict_items'>
總結:

Python2.7中,iteritems()返回操作列表的迭代器
Python3 iteritems()方法廢除,使用items替換,可以用for遍歷 哦~

10.nonlocal

Python2.7

def function():
	num = 2
	def fun2():
		print 'fun2',num
		num = 5
		print 'fun22',num
	print 'function3',num
	fun2()
	print 'function4',num
function()

**Python3 **

def function():
	num = 2
	def fun2():
		nonlocal num
		print('fun2 nonlocal',num)
		num = 5
		print('fun2 local',num)
	print('function local',num)
	fun2()
	print('function local',num)
function()

最後一個nonlocal的我沒有測試,如果你們有測試的結果然後觀察一下區別,如果樂意分享一下的話,非常歡迎 ^ 0 ^~
祈禱疫情快快消失 ~~~~~~ over ~~~~~~~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章