python2.x和python3.x主要的差异

参考:
https://nbviewer.jupyter.org/github/rasbt/python_reference/blob/master/tutorials/key_differences_between_python_2_and_3.ipynb#The-next-function-and-next-method

1.信息打印的区别,python3需要以函数的方式调用,而python2不需要

%%script python2
a = (2, 3)
print a
(2, 3)
%%script python3
a = (2, 3)
print a
File "<stdin>", line 2
    print a
          ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(a)?
%%script python3
a = (2, 3)
print(a)
(2, 3)

2.整数除法的区别

python2默认是整除,python3默认是非整除

%%script python2
a = 2 / 1
b = 2 // 1
c = 2 / 1.0
print a,b,c
2 2 2.0
%%script python3
a = 2 / 1
b = 2 // 1
c = 2 / 1.0
print(a,b,c)
2.0 2 2.0

3.字符串存储的区别,python3默认将字符串存储为unicode形式,而python2则是ASCLL方式,存储为unicode需要显式指定u’’ ,python3增加了两个类型,byte类型和bytearray类型

%%script python2
s = "I am Chinese."
print type(s)
s = u"I am Chinese."
print type(s)
<type 'str'>
<type 'unicode'>

python3 字符串当前类型都为unicode

并增加了byte类型和bytearray类型

%%script python3
import sys
print('Python %s.%s.%s' %sys.version_info[:3])
a = "I am Chinese."
b = "我是中国人"
c = a + b
print(type(a),type(b),c)
d = b' bytes for storing data'
print(type(d))
e = bytearray(b'bytearrays')
print(type(e))
Python 3.7.0
<class 'str'> <class 'str'> I am Chinese.我是中国人
<class 'bytes'>
<class 'bytearray'>

4.异常处理的区别,抛出异常和接收异常表达方式存在差异

%%script python2
try:
    a = 1 / 0
except Exception, err:
    print err
try:
    inputValue="test"
    if type(inputValue)!=type(1):
        raise ValueError,"input value is not a interger"
    else:
        print inputValue
except ValueError, err:
    print err
integer division or modulo by zero
input value is not a interger

区别主要在1) raise ValueError(“input value is not a interger”) 2) except ValueError as err:

%%script python3
try:
    a = 1 / 0
except Exception as err:
    print(err)

try:
    inputValue="test"
    if type(inputValue)!=type(1):
        raise ValueError("input value is not a interger")
    else:
        print(inputValue)
except ValueError as err:
    print(err)
division by zero
input value is not a interger

5.在列表推导式中,循环变量的作用域的区别

%%script python2
i = 1
print 'before: i =', i
print 'comprehension: ', [i for i in range(5)]
print 'after: i =', i
before: i = 1
comprehension:  [0, 1, 2, 3, 4]
after: i = 4
%%script python3
i = 1
print('before: i =', i)
print('comprehension: ', [i for i in range(5)])
print('after: i =', i)
before: i = 1
comprehension:  [0, 1, 2, 3, 4]
after: i = 1

6.在python3中取消了xrange函数,统一使用range

在python3中range的表现跟python2中的xrange类似

%%script python2
a =[i for i in xrange(10)]
print a
print range(10)
print xrange(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
xrange(10)
%%script python3
a =[i for i in xrange(10)]
print(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'xrange' is not defined
%%script python3
a =[i for i in range(10)]
print(a)
print(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(0, 10)

7.对于可迭代的对象,python3没有.next()方法,只有next();而python2两者都支持

%%writefile text.txt 
a
b
c
d
e
Writing text.txt
%%script python2
f = open("text.txt","r")
print f.next()
print next(f)
a

b
%%script python3
f = open("text.txt","r")
print(next(f))
print(f.next())
a

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
AttributeError: '_io.TextIOWrapper' object has no attribute 'next'

8.当比较不可比较的对象时,python3会抛出TypeError的异常

%%script python2
print [1, 2] > 'foo'
print (1, 2) > 'foo'
print [1, 2] > (1, 2)
False
True
False
%%script python3
try:
    print([1, 2] > 'foo')
except TypeError as err:
    print(err)
try:
    print((1, 2) > 'foo')
except TypeError as err:
    print(err)
try:
    print([1, 2] > (1, 2))
except TypeError as err:
    print(err)
'>' not supported between instances of 'list' and 'str'
'>' not supported between instances of 'tuple' and 'str'
'>' not supported between instances of 'list' and 'tuple'

9.在python3中input()函数接收的对象都会以str类型存储,而python2则会根据具体输入形式以与该形式相符合的方式进行存储

Python 2.7.6 
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> 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'>
Python 3.7.0 (default, Sep 18 2018, 18:47:22)
[Clang 9.1.0 (clang-902.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> my_input = input('enter a number: ')
enter a number: 123
>>> type(my_input)
<class 'str'>
>>> my_input = raw_input('enter a number: ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'raw_input' is not defined

10.python3对于很多可迭代目标它会直接返回可迭代目标,而不是list,对于只需要用一次的数据这样可以节约内存,但是对于需要多次使用的数据这样做可能会影响效率。对于后者可以显式使用list函数。

%%script python3
print(range(10))
print(list(range(10)))
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]



转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 524813168@qq.com

文章标题:python2.x和python3.x主要的差异

文章字数:1.3k

本文作者:xieweihao

发布时间:2019-11-13, 17:20:48

最后更新:2019-11-13, 17:29:28

原始链接:http://weihaoxie.com/post/b8f3def3.html

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏