月嫂的个人简历网站模板,商标自动生成免费软件,网站合同需要注意什么呢,二级域名搜索使用Python时都需要安装相应的版本#xff0c;不同的版本适用性也不一样。今天从除法算子、打印功能、Unicode、Xrange、错误处理、未来模块方面看看Python2.x和Python3.x之间的区别。除法算子在移植代码或在python2.x中执行python3.x代码时#xff0c;要注意整数除法的更改不同的版本适用性也不一样。今天从除法算子、打印功能、Unicode、Xrange、错误处理、未来模块方面看看Python2.x和Python3.x之间的区别。除法算子在移植代码或在python2.x中执行python3.x代码时要注意整数除法的更改最好使用浮动值(如7.0/5或7/5.0)来获得预期的结果。print 7 / 5print -7 / 5Output in Python 2.x1-2Output in Python 3.x :1.4-1.4打印功能print关键字在Python2.x中被打印()函数在Python3.x中。如果在Python 2之后添加了空格解释器将其计算为表达式则括号在Python 2中起作用。注意如果在python 3.x中不使用括号我们就会得到SyntaxError。print Hello, Geeks # Python 3.x doesnt supportprint(Hope You like these facts)Output in Python 2.x :Hello, GeeksHope You like these factsOutput in Python 3.x :File a.py, line 1print Hello, Geeks^SyntaxError: invalid syntaxUnicode在Python 2中隐式str类型是ASCII。在Python3.x中隐式str类型是Unicode。print(type(default string ))print(type(bstring with b ))Output in Python 2.x (Bytes is same as str)Output in Python 3.x (Bytes and str are different)Python2.x也支持Unicodeprint(type(default string ))print(type(ustring with b ))Output in Python 2.x (Unicode and str are different)Output in Python 3.x (Unicode and str are same)XrangePython2.x的xrange()在Python3.x中不存在。在Python2.x中Range返回一个列表即range(3)返回[012]而xrange返回xrange对象即xrange(3)返回与Java迭代器类似的迭代器对象并在需要时生成数字。range()需要多次迭代相同的序列提供了一个静态列表。Xrange()需要每次都重新构造序列。Xrange()不支持片和其他列表方法。Xrange()的优点当任务在一个大范围内迭代时节省内存。在Python3.x中Range函数执行Python2.x中的xrange函数坚持使用Range保持代码的可移植性for x in xrange(1, 5):print(x),for x in range(1, 5):print(x),Output in Python 2.x1 2 3 4 1 2 3 4Output in Python 3.xNameError: name xrange is not defined错误处理在python 3.x中必须要使用“as”关键字。try:trying_to_check_errorexcept NameError, err:print err, Error Caused # Would not work in Python 3.xOutput in Python 2.x:name trying_to_check_error is not defined Error CausedOutput in Python 3.x :File a.py, line 3except NameError, err:^SyntaxError: invalid syntaxtry:trying_to_check_errorexcept NameError as err: # as is needed in Python 3.xprint (err, Error Caused)Output in Python 2.x:(NameError(name trying_to_check_error is not defined,), Error Caused)Output in Python 3.x :name trying_to_check_error is not defined Error Caused_模块__WORWORY__模块帮助迁移到Python3.x。如果想在2.x代码中支持Python3.x使用__future__在我们的代码中导入。例如在下面的Python2.x代码中我们使用Python3.x的整数除法行为。# In below python 2.x code, division works# same as Python 3.x because we use __future__from __future__ import divisionprint 7 / 5print -7 / 5产出1.4-1.4在Python2.x中使用方括号的另一个例子是_WORWORY__模块from __future__ import print_functionprint(GeeksforGeeks)产出GeeksforGeeks