Python 2和3之间的区别

Here you will know about difference between python 2 and 3.

在这里,您将了解python 2和3之间的区别。

As a newbie, everyone confuses that which version of Python should learn and use (Python 2.x or 3.x, where x means versions). Let’s see the key differences between them.

作为新手,每个人都会混淆应该学习和使用哪个版本的Python(Python 2.x或3.x,其中x表示版本)。 让我们看看它们之间的主要区别。

Python 2 vs 3 - Difference between Python 2 and 3

Image Source

图片来源

Python 2 vs 3 – Python 2和3之间的区别 (Python 2 vs 3 – Difference between Python 2 and 3)

 Python 2Python 3
1. Integer Divisionprint 9/2

>> 4

print(9/2)

>> 4.5

2. Print functionprint “Hello world”

>>Hello world

print(“Hello world”)

>>Hello world

3. Unicodeprint type(Unicode(“Hello”))

>>  <type ‘unicode’>

print type(b’Hello’)

>> <type ‘str’>

print ‘hello’ +  b’ world’

>>hello world

print type(bytearray(b’hello world’))

>> <type ‘bytearray’> 

print (‘\u03BCnico\u394e!’)

>> µnico∆e!

print(type(b’hello’))

>> <class ‘bytes’>

print(‘hello’ + b’ world’))

>> TypeError

print(type(bytearray(b’hello’)))

>> <class ‘bytearray’>

4. xrange functionSupport range() and xrange() both.have no xrange() function but range() function will behave like xrange() in python 2.
5. Raising exceptionraise IOError, “file not found”

>>IOError: file not found

raise IOError(“file not found”)

>>IOError: file not found                           

6. Handling exceptiontry:

  print 4/0

except ZeroDivisionError, err:

  print “can’t divide by zero”

  print “error – “ + err

output:

can’t divide by zero

error – integer division or modulo by zero

try:

  print(4/0)

except ZeroDivisionError as err:

  print(“can’t divide by zero”)

  print(“error –“ + str(err))

output:

can’t divide by zero

error – division by zero

7. Leak of for-loop variables in global namespacei = 1

print ‘before: i = ‘, i

print ‘loop:’,[i for i in range(5)]

print ‘after:i = ‘, i

Output:

before: i =1

loop: [0,1,2,3,4]

after: i = 4

i = 1

print(‘before :i =’, i)

print(‘loop:’ [i for i in range(5)])

print(‘after: i = ‘, i)

Output:

before: i = 1

loop: [0,1,2,3,4]

after: i = 1

8. .next() methodhave next() function and .next() method for iterate next element.

list1 = [4, 43, 34,  32]

iterator = iter(list1)

print iterator.next()

print next(iterator)

print iterator.next()

Output:

4

43

34

Have only next() function.

list1 = [4, 43, 34, 32]

iterator = iter(list1)

print (next(iterator))

print (next(iterator))

print (next(iterator))

Output:

4

43

34

9. input() methodWe can use both raw_input() and input() method.

s = raw_input(“enter something:”)

raw_input() is replaced by input() method. There is no raw_input() method.

s = input(“enter something:”)

Python 2 Python 3
1.整数部 打印9/2

>> 4

打印(9/2)

>> 4.5

2.打印功能 打印“ Hello world”

>>你好世界

打印(“ Hello world”)

>>你好世界

3. Unicode 打印类型(Unicode(“ Hello”))

>> <类型'unicode'>

打印类型(b'Hello')

>> <类型'str'>

打印'hello'+ b'world'

>>你好世界

打印类型(bytearray(b'hello world'))

>> <类型'bytearray'>  

打印('\ u03BCnico \ u394e!')

>> µnico∆e!

打印(类型(b'hello'))

>> <class'bytes'>

print('hello'+ b'world'))

>> TypeError

打印(类型(字节数组(b'hello')))

>> <class'bytearray'>

4. xrange功能 同时支持range()和xrange()。 没有xrange()函数,但range()函数的行为类似于python 2中的xrange()。
5.引发异常 引发IOError,“找不到文件”

>> IOError:找不到文件

引发IOError(“找不到文件”)

>> IOError:找不到文件

6.处理异常 尝试:

打印4/0

除了ZeroDivisionError,错误:

打印“不能被零除”

打印“错误–” +错误

输出:

不能被零除

错误–整数除或以零为模

尝试:

打印(4/0)

除了ZeroDivisionError作为err:

打印(“不能被零除”)

打印(“错误–” + str(err))

输出:

不能被零除

错误–除以零

7.全局命名空间中的for循环变量泄漏 我= 1

在'i ='之前打印'

打印“循环:”,[i代表范围(5)中的i]

打印'after:i =',i

输出:

之前:我= 1

循环:[0,1,2,3,4]

之后:i = 4

我= 1

print('before:i =',i)

print('loop:'[i for i in range(5)])

print('after:i =',i)

输出:

之前:i = 1

循环:[0,1,2,3,4]

之后:i = 1

8. .next()方法 具有next()函数和.next()方法来迭代下一个元素。

list1 = [4、43、34、32]

迭代器= iter(list1)

打印iterator.next()

打印下一个(迭代器)

打印iterator.next()

输出:

4

43

34

仅具有next()函数。

list1 = [4、43、34、32]

迭代器= iter(list1)

打印(下一个(迭代器))

打印(下一个(迭代器))

打印(下一个(迭代器))

输出:

4

43

34

9. input()方法 我们可以同时使用raw_input()和input()方法。

s = raw_input(“输入内容:”)

raw_input()被input()方法替换。 没有raw_input()方法。

s =输入(“输入内容:”)

Let’s understand these differences in detail.

让我们详细了解这些差异。

1. Integer Division:-

1.整数科:

In python 2 if we perform division on two integers then the output will be an integer too. But in python 3, output will be accurate, so the result can be in float too. Still want the result in integer, then you can use print(9//2) it return an integer result.

在python 2中,如果我们对两个整数执行除法运算,则输出也将是一个整数。 但是在python 3中,输出将是准确的,因此结果也可以是float。 仍然想要整数形式的结果,则可以使用print(9 // 2)返回整数结果。

2. Print Function:-

2.打印功能:

In python 2 parenthesis aren’t compulsory to use we can print anything without using parenthesis but in Python 3 it is compulsory to use parenthesis otherwise it will raise error.

在python 2中,不强制使用括号,我们可以不使用括号就打印任何内容,但是在Python 3中,必须使用括号,否则会引起错误。

3. Unicode:-

3. Unicode:

Python 2 has ASCII str() Types, separate Unicode but it doesn’t have byte type.

Python 2具有ASCII str()类型,单独的Unicode,但没有字节类型。

But in Python 3 we have Unicode (utf-8: 8 means it uses 8-bit block to represent a character) strings and also 2 byte classes that are bytearray and byte.

但是在Python 3中,我们具有Unicode(utf-8:8表示它使用8位块表示字符)字符串以及2个字节类,分别是bytearraybyte。

Python 2 treats string and bytes as same, so we can also concatenate them. But in Python 3 we can’t concatenate a byte array with strings, because both are different for python 3.

Python 2将字符串和字节视为相同,因此我们也可以将它们连接起来。 但是在Python 3中,我们无法将字节数组与字符串连接起来,因为python 3两者都不同

4. xrange function:-

4. xrange功能:

python 2 has two handy function for creating a range of integers  that is used in for loop, these are range and xrange. They both provide a way to generate a list of integers. So for the most part, xrange and range are the exact same in terms of functionality. The only difference is that range returns a Python List object and xrange returns an xrange object. range function creates an array of integers, so it will take much memory if we create a range of millions, which can result MemoryError and crash your program. So xrange is the function to use if you’ve a really memory sensitive system such as cell phone.

python 2具有两个方便的函数,用于创建在for循环中使用的整数范围,它们是rangexrange 。 它们都提供了一种生成整数列表的方法。 因此,在大多数情况下, xrangerange在功能方面完全相同。 唯一的区别是range返回一个Python List对象,而xrange返回一个xrange对象。 range函数创建一个整数数组,因此,如果我们创建一个数百万的范围,它将占用大量内存,这可能导致MemoryError并使程序崩溃。 因此,如果您拥有真正的内存敏感系统(例如手机),则可以使用xrange函数。

But in python 3 there is no xrange function, the range function will work as xrange in python 2.

但是在python 3中没有xrange函数, range函数将在python 2中像xrange一样工作。

Example:

例:

#program in python 3

#python 3中的程序

for i in range(1,10):

对于范围(1,10)中的i:

  print(i)

打印(i)

#program in python 2

#python 2中的程序

for i in xrange(1,10):

对于我在xrange(1,10)中:

  print i

打印我

Output

输出量

1

1个

2

2

3

3

4

4

5

5

6

6

7

7

8

8

9 

9  

5. Raising exception:-

5.引发例外:

as we’ve seen the difference between print function, raising an exception will follow the same syntax.

正如我们已经看到的打印功能之间的差异,引发异常将遵循相同的语法。

In python 2, its

在python 2中,

raise IOError, “file not found”

引发IOError,“找不到文件”

In python 3, its

在python 3中

raise IOError(“file not found”)

引发IOError(“找不到文件”)

6. Handling exception:-

6.处理异常:

there is a minor change in syntax, we’ve to use as keyword in python 3.

语法略有变化,我们必须在python 3中使用as作为关键字。

In python 2, its

在python 2中,

except IOError, err:

除了IOError,错误:

In python 3, its

在python 3中

except IOError as err: 

除了IOError作为err:  

7. Leak of for-loop variables in global namespace:-

7.全局命名空间中的for循环变量泄漏:

In python 2 there was a problem that value of a global variable had changed while using that variable in for-loop.

在python 2中,存在一个问题,即在for循环中使用该变量时,全局变量的值已更改。

But in Python 3, for loop variables don’t leak into the global namespace anymore!

但是在Python 3中,for循环变量不再泄漏到全局名称空间中!

8. .next() method:-

8. .next()方法:-

Python have .next() method and next() function to fetch the next element of an iterator.

Python具有.next()方法和next()函数来获取迭代器的下一个元素。

But in python 3 .next() method is no more. We have to use only next() function to iterate the next element of iterator.

但是在python 3中,.next()方法不再可用。 我们只需要使用next()函数来迭代迭代器的下一个元素。

9.input() method:-

9.input()方法:-

python 2 have input() and raw_input() methods for taking input. The difference between them raw_input() returns a string, and input() tries to run the input as a python expression.

python 2具有input()和raw_input()方法来获取输入。 它们之间的区别raw_input()返回一个字符串,而input()尝试将输入作为python表达式运行。

Mostly all we want the string as input then we convert it into any datatype as we want.

大多数情况下,我们都希望将字符串作为输入,然后根据需要将其转换为任何数据类型。

In python 3 there is no raw_input() method. The raw_input() method is replaced by input() in python 3. If you still want to use the input() method like in python 2 then we can use eval() method.

在python 3中,没有raw_input()方法。 在python 3中,raw_input()方法已由input()替换。如果仍要像在python 2中一样使用input()方法,则可以使用eval()方法。

eval(input(“enter something:”))

eval(input(“输入一些东西:”))

it will work as same as input() in python 2.

它将与python 2中的input()相同。

There are many other differences between python 2 and python 3 like

python 2和python 3之间还有许多其他区别,例如

10. The __future__ Module:-

10.未来模块:

as we know there are many things that python 3 supports but python 2 don’t. if you’re planning python 3 support for your code then use __future__ module.

我们知道python 3支持很多东西,但是python 2不支持。 如果您打算为代码提供python 3支持,请使用__future__模块。

Let’s say we want python 3’s integer division behavior in our python 2 program then our program will look like

假设我们要在python 2程序中使用python 3的整数除法行为,则程序看起来像

from  __future__ import division

来自__future__进口部门

print 9/2

打印9/2

output:

输出:

4.5

4.5

without __future__ module

没有__future__模块

Print 9/2

打印9/2

Output:

输出:

4 

4  

11. Libraries:-

11.图书馆:

The advantage to use python 2 is it have a large number of libraries. Python 2 is still the default in many operating systems like ubuntu 14.04 and 16.04 LTS. But python 3 is also developing day by day, all the future developments will be implement in python 3 rather than the python 2.

使用python 2的优点是它具有大量的库。 在许多操作系统(例如ubuntu 14.04和16.04 LTS)中,Python 2仍然是默认设置。 但是python 3也在日益发展,所有未来的发展都将在python 3中实现,而不是在python 2中实现。

So if you’re completely beginner then we recommend python 3 because it is the future of Python and it is easy as python 2 to learn and python 3 has some additional features (eg. Function memoiziation).

因此,如果您完全是新手,那么我们建议您使用python 3,因为它是Python的未来,并且很容易学习python 2,并且python 3具有一些其他功能(例如,功能记忆)。

Comment below if you have queries related to above tutorial for difference between python 2 and 3.

如果您对以上教程有关于python 2和3之间差异的疑问,请在下面评论。

翻译自: https://www.thecrazyprogrammer.com/2018/01/difference-python-2-3.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值