Python 2 vs Python 3: краткий обзор и практические соображения
Python – это многофункциональный язык программирования для разработки различных программных проектов. Python вышел в свет в 1991 и назван в честь британской комик-группы Monty Python: так разработчики хотели подчеркнуть, что этот язык программирования настолько прост в использовании, что это даже смешно. Простота установки, относительно понятный синтаксис, немедленное сообщение об ошибках – благодаря таким своим качествам Python является отличным решением как для новичков, так и для опытных разработчиков.
Python является мультипарадигмальным языком программирования (это значит, что он поддерживает несколько стилей программирования, включая объектно-ориентированное программирование и написание сценариев), а потому его можно применить в разработке практически любого проекта. Python всё чаще используется в промышленности такими организациями, как United Space Alliance (главная поддержка шаттлов НАСА) и Industrial Light & Magic (студия анимации Lucasfilm). Python предлагает много возможностей для тех, кто хочет подобрать мощный дополнительный язык программирования.
Язык Python был разработан в поздние 80-е и вышел в 1991 году; его автором является Гвидо ван Россум (Guido van Rossum).
Python разрабатывался как преемник языка программирования ABC, его первая версия уже включала обработку исключений, функции и классы с наследованием. После создания в 1994 году форума конференции Usenet под названием comp.lang.python база пользователей Python значительно выросла, благодаря чему Python стал одним из самых популярных языков программирования для разработки программ с открытым исходным кодом.
Краткий обзор
Прежде чем перейти к потенциальным возможностям и ключевым программным различиям между Python 2 и Python 3, давайте ознакомимся с особенностями этих релизов Python.
Python 2
Вышедшая в 2000 году версия Python 2 сделала процесс разработки более прозрачным и всеобъемлющим по сравнению с предыдущими версиями Python с реализацией PEP.
Примечание: PEP (Python Enhancement Proposal) – техническая спецификация, которая предоставляет информацию членам сообщества Python или же описывает новую функцию языка.
Кроме того, Python 2 предложил множество новых функций: циклический сборщик мусора для автоматизации управления памятью, расширенную поддержку Unicode для стандартизации символов, списковую сборку и т.п. По мере разработки Python 2 набор функций значительно расширился, в том числе появилась унификация типов и классов Python (версия 2.2).
Python 3
Python 3, последняя разрабатываемая версия, уже считается будущим этого языка программирования. Python 3 был выпущен в конце 2008 года, его целью было устранение внутренних конструктивных недостатков предыдущих версий языка. Python 3 сосредоточен на поддержке чистой базы кода и устранении избыточности.
Основные изменения в Python 3.0: замена оператора print встроенной функцией, улучшение способа деления целых чисел и продвинутая поддержка Unicode.
Сначала Python 3 восприняли прохладно, поскольку он не был совместим с Python 2, а это заставляло пользователей делать выбор между привычной и новой версиями языка. Кроме того, многие библиотеки были доступны только для Python 2; но когда команда разработчиков Python 3 подтвердила, что поддержка Python 2 прекращается, большинство библиотек было адаптировано для Python 3.
Python 2.7
Версия Python 2.7 вышла 3 июля 2010 года и должна была стать последней версией Python 2.х.
Версия Python 2.7 была предназначена для пользователей Python 2.х, которым трудно перейти на новую версию, Python 3, и должна была обеспечить совместимость этих версий. Она предоставляла усовершенствованные модули для версии 2.7 (например unittest для поддержки автоматизации тестирования, argparse для разбора параметров командной строки, а также более удобные классы – коллекции).
Таким образом, версия Python 2.7 оказалась в уникальном положении: он стал связующим звеном между Python 2 и Python 3.0, благодаря своей совместимости со многими надежными библиотеками он получил популярность среди программистов. Как правило, сегодня при упоминании Python 2 имеется в виду именно версия Python 2.7.
Версия Python 2.7 по-прежнему остаётся в разработке, которая на данный момент почти полностью состоит из исправлений багов и будет полностью прекращена в 2020 году.
Ключевые различия
Python 2.7 и Python 3 имеют много общих возможностей, однако их не следует воспринимать как взаимозаменяемые версии. Конечно, вы можете писать хороший код и полезные программы в любой из этих версий, однако следует помнить о серьёзных различиях в синтаксисе и обработке.
Ниже мы рассмотрим несколько общих примеров, но, скорее всего, вы столкнётесь с гораздо большим количеством различий, постоянно работая в Python.
В Python 2 print является оператором, а в Python 3 – встроенной функцией. К примеру, чтобы вывести в Python 2 предложение Sharks are my favorite sea creatures, вы можете использовать следующую команду:
print «Sharks are my favorite sea creatures»
В Python 3 print() является функцией, потому, чтобы вывести такое предложение, нужно ввести:
print(«Sharks are my favorite sea creatures»)
Благодаря этому изменению синтаксис языка Python стал более последовательным. Теперь синтаксис функции print() совместим с Python 2.7.
Деление целых чисел
В Python 2 целым считалось любое число, введённое без десятичных знаков. На первый взгляд, это довольно простой способ обработки. Однако при попытке поделить одно целое число на другое бывает результат с плавающей точкой, например:
Но целые числа в Python 2 не могли изменить свой тип, а потому не могли использовать плавающую точку.
Когда два числа по обе стороны символа деления являются целыми числами, деление floor, то есть, для фактора х Python 2 возвращает наибольшее целое число меньше или равное х. К примеру, при делении 5 / 2 таким числом будет 2.
a = 5 / 2
print a
2
Чтобы обойти эту проблему, можно добавить десятичные знаки, 5.0 / 2.0, и тогда Python 2 вернет 2.5.
В Python 3 деление целых чисел становится понятнее.
a = 5 / 2
print(a)
2.5
Чтобы выполнить деление floor и получить только целую часть числа, нужно использовать следующий синтаксис Python 3:
b = 5 // 2
print(b)
2
Это изменение в Python 3 значительно улучшило деление целых чисел.
Поддержка Unicode
Языки программирования обрабатывать строковый тип (то есть последовательность символов) несколькими различными способами, благодаря чему компьютеры могут преобразовывать числа в буквы и другие символы.
По умолчанию Python 2 использует алфавит ASCII. ASCII даже с расширениями ограничен парой сотен символов, и, очевидно, является не самым гибким методом кодирования, особенно это касается символов, не относящихся к английскому алфавиту.
Более универсальный и надежный метод кодировки символов Unicode поддерживает более 128 000 символов. Чтобы использовать Unicode, в Python 2 нужно начинать строку с префикса u, например:
Python 3 использует Unicode по умолчанию. Это не только экономит время разработчика, но и открывает доступ к огромному набору символов. Unicode поддерживает разнообразные символы и эмодзи, а также гарантирует поддержку проекта на мобильных устройствах.
Если вы хотите сделать код Python 3 обратно совместимым с Python 2, вы можете по-прежнему использовать префикс u.
Постоянная поддержка
Самым большим различием между Python 3 и Python 2 является не синтаксис, а тот факт, что Python 2.7 потеряет постоянную поддержку в 2020 году, а Python 3 будет продолжать развиваться, в результате чего он получит более широкие возможности и большее количество исправлений ошибок.
Новейшие разработки посвящены отформатированным строковым литералам, упрощению настройки создания класса и синтаксического способа обработки матричного умножения.
Остающаяся в разработке версия Python 3 предоставляет пользователям своевременное исправление багов и более производительные программы.
Заключение
Python – многофункциональный и хорошо задокументированный язык программирования.
Хотя между Python 2 и Python 3 существует несколько значительных различий, перейти с одной версии на другую очень просто, это требует лишь небольшой дополнительной настройки. Более того, код Python 3 обычно можно запустить и в Python 2.7.
Важно понимать, что чем больше разработчиков будет использовать Python 3, тем быстрее Python 3 будет совершенствоваться и расширяться, учитывая требования своих пользователей.
What’s New In Python 3.0¶
This article explains the new features in Python 3.0, compared to 2.6. Python 3.0, also known as “Python 3000” or “Py3K”, is the first ever intentionally backwards incompatible Python release. Python 3.0 was released on December 3, 2008. There are more changes than in a typical release, and more that are important for all Python users. Nevertheless, after digesting the changes, you’ll find that Python really hasn’t changed all that much – by and large, we’re mostly fixing well-known annoyances and warts, and removing a lot of old cruft.
This article doesn’t attempt to provide a complete specification of all new features, but instead tries to give a convenient overview. For full details, you should refer to the documentation for Python 3.0, and/or the many PEPs referenced in the text. If you want to understand the complete implementation and design rationale for a particular feature, PEPs usually have more details than the regular documentation; but note that PEPs usually are not kept up-to-date once a feature has been fully implemented.
Due to time constraints this document is not as complete as it should have been. As always for a new release, the Misc/NEWS file in the source distribution contains a wealth of detailed information about every small thing that was changed.
Common Stumbling Blocks¶
This section lists those few changes that are most likely to trip you up if you’re used to Python 2.5.
Print Is A Function¶
The print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement ( PEP 3105). Examples:
You can also customize the separator between items, e.g.:
The print() function doesn’t support the “softspace” feature of the old print statement. For example, in Python 2.x, print "A\n", "B" would write "A\nB\n" ; but in Python 3.0, print("A\n", "B") writes "A\n B\n" .
Initially, you’ll be finding yourself typing the old print x a lot in interactive mode. Time to retrain your fingers to type print(x) instead!
When using the 2to3 source-to-source conversion tool, all print statements are automatically converted to print() function calls, so this is mostly a non-issue for larger projects.
Views And Iterators Instead Of Lists¶
Some well-known APIs no longer return lists:
dict methods dict.keys() , dict.items() and dict.values() return “views” instead of lists. For example, this no longer works: k = d.keys(); k.sort() . Use k = sorted(d) instead (this works in Python 2.5 too and is just as efficient).
Also, the dict.iterkeys() , dict.iteritems() and dict.itervalues() methods are no longer supported.
map() and filter() return iterators. If you really need a list and the input sequences are all of equal length, a quick fix is to wrap map() in list() , e.g. list(map(. )) , but a better fix is often to use a list comprehension (especially when the original code uses lambda ), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).
If the input sequences are not of equal length, map() will stop at the termination of the shortest of the sequences. For full compatibility with map() from Python 2.x, also wrap the sequences in itertools.zip_longest() , e.g. map(func, *sequences) becomes list(map(func, itertools.zip_longest(*sequences))) .
range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.
zip() now returns an iterator.
Ordering Comparisons¶
Python 3.0 has simplified the rules for ordering comparisons:
The ordering comparison operators ( < , <= , >= , > ) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, expressions like 1 < » , 0 > None or len <= len are no longer valid, and e.g. None < None raises TypeError instead of returning False . A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other. Note that this does not apply to the == and != operators: objects of different incomparable types always compare unequal to each other.
builtin.sorted() and list.sort() no longer accept the cmp argument providing a comparison function. Use the key argument instead. N.B. the key and reverse arguments are now “keyword-only”.
The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__() , and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) — (a < b) as the equivalent for cmp(a, b) .)
Integers¶
PEP 237: Essentially, long renamed to int . That is, there is only one built-in integral type, named int ; but it behaves mostly like the old long type.
PEP 238: An expression like 1/2 returns a float. Use 1//2 to get the truncating behavior. (The latter syntax has existed for years, at least since Python 2.2.)
The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
The repr() of a long integer doesn’t include the trailing L anymore, so code that unconditionally strips that character will chop off the last digit instead. (Use str() instead.)
Octal literals are no longer of the form 0720 ; use 0o720 instead.
Text Vs. Data Instead Of Unicode Vs. 8-bit¶
Everything you thought you knew about binary data and Unicode has changed.
Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. All text is Unicode; however encoded Unicode is represented as binary data. The type used to hold text is str , the type used to hold data is bytes . The biggest difference with the 2.x situation is that any attempt to mix text and data in Python 3.0 raises TypeError , whereas if you were to mix Unicode and 8-bit strings in Python 2.x, it would work if the 8-bit string happened to contain only 7-bit (ASCII) bytes, but you would get UnicodeDecodeError if it contained non-ASCII values. This value-specific behavior has caused numerous sad faces over the years.
As a consequence of this change in philosophy, pretty much all code that uses Unicode, encodings or binary data most likely has to change. The change is for the better, as in the 2.x world there were numerous bugs having to do with mixing encoded and unencoded text. To be prepared in Python 2.x, start using unicode for all unencoded text, and str for binary or encoded data only. Then the 2to3 tool will do most of the work for you.
You can no longer use u". " literals for Unicode text. However, you must use b". " literals for binary data.
As the str and bytes types cannot be mixed, you must always explicitly convert between them. Use str.encode() to go from str to bytes , and bytes.decode() to go from bytes to str . You can also use bytes(s, encoding=. ) and str(b, encoding=. ) , respectively.
Like str , the bytes type is immutable. There is a separate mutable type to hold buffered binary data, bytearray . Nearly all APIs that accept bytes also accept bytearray . The mutable API is based on collections.MutableSequence .
All backslashes in raw string literals are interpreted literally. This means that ‘\U’ and ‘\u’ escapes in raw strings are not treated specially. For example, r’\u20ac’ is a string of 6 characters in Python 3.0, whereas in 2.6, ur’\u20ac’ was the single “euro” character. (Of course, this change only affects raw string literals; the euro character is ‘\u20ac’ in Python 3.0.)
The built-in basestring abstract type was removed. Use str instead. The str and bytes types don’t have functionality enough in common to warrant a shared base class. The 2to3 tool (see below) replaces every occurrence of basestring with str .
Files opened as text files (still the default mode for open() ) always use an encoding to map between strings (in memory) and bytes (on disk). Binary files (opened with a b in the mode argument) always use bytes in memory. This means that if a file is opened using an incorrect mode or encoding, I/O will likely fail loudly, instead of silently producing incorrect data. It also means that even Unix users will have to specify the correct mode (text or binary) when opening a file. There is a platform-dependent default encoding, which on Unixy platforms can be set with the LANG environment variable (and sometimes also with some other platform-specific locale-related environment variables). In many cases, but not all, the system default is UTF-8; you should never count on this default. Any application reading or writing more than pure ASCII text should probably have a way to override the encoding. There is no longer any need for using the encoding-aware streams in the codecs module.
The initial values of sys.stdin , sys.stdout and sys.stderr are now unicode-only text files (i.e., they are instances of io.TextIOBase ). To read and write bytes data with these streams, you need to use their io.TextIOBase.buffer attribute.
Filenames are passed to and returned from APIs as (Unicode) strings. This can present platform-specific problems because on some platforms filenames are arbitrary byte strings. (On the other hand, on Windows filenames are natively stored as Unicode.) As a work-around, most APIs (e.g. open() and many functions in the os module) that take filenames accept bytes objects as well as strings, and a few APIs have a way to ask for a bytes return value. Thus, os.listdir() returns a list of bytes instances if the argument is a bytes instance, and os.getcwdb() returns the current working directory as a bytes instance. Note that when os.listdir() returns a list of strings, filenames that cannot be decoded properly are omitted rather than raising UnicodeError .
Some system APIs like os.environ and sys.argv can also present problems when the bytes made available by the system is not interpretable using the default encoding. Setting the LANG variable and rerunning the program is probably the best approach.
PEP 3138: The repr() of a string no longer escapes non-ASCII characters. It still escapes control characters and code points with non-printable status in the Unicode standard, however.
PEP 3120: The default source encoding is now UTF-8.
PEP 3131: Non-ASCII letters are now allowed in identifiers. (However, the standard library remains ASCII-only with the exception of contributor names in comments.)
The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
See also the Unicode HOWTO , which was updated for Python 3.0.
Overview Of Syntax Changes¶
This section gives a brief overview of every syntactic change in Python 3.0.
New Syntax¶
PEP 3107: Function argument and return value annotations. This provides a standardized way of annotating a function’s parameters and return value. There are no semantics attached to such annotations except that they can be introspected at runtime using the __annotations__ attribute. The intent is to encourage experimentation through metaclasses, decorators or frameworks.
PEP 3102: Keyword-only arguments. Named parameters occurring after *args in the parameter list must be specified using keyword syntax in the call. You can also use a bare * in the parameter list to indicate that you don’t accept a variable-length argument list, but you do have keyword-only arguments.
Keyword arguments are allowed after the list of base classes in a class definition. This is used by the new convention for specifying a metaclass (see next section), but can be used for other purposes as well, as long as the metaclass supports it.
PEP 3104: nonlocal statement. Using nonlocal x you can now assign directly to a variable in an outer (but non-global) scope. nonlocal is a new reserved word.
PEP 3132: Extended Iterable Unpacking. You can now write things like a, b, *rest = some_sequence . And even *rest, a = stuff . The rest object is always a (possibly empty) list; the right-hand side may be any iterable. Example:
This sets a to 0 , b to 4 , and rest to [1, 2, 3] .
Dictionary comprehensions:
Set literals, e.g. <1, 2>. Note that <> is an empty dictionary; use set() for an empty set. Set comprehensions are also supported; e.g.,
New octal literals, e.g. 0o720 (already in 2.6). The old octal literals ( 0720 ) are gone.
New binary literals, e.g. 0b1010 (already in 2.6), and there is a new corresponding built-in function, bin() .
Bytes literals are introduced with a leading b or B , and there is a new corresponding built-in function, bytes() .
Changed Syntax¶
as and with are now reserved words. (Since 2.6, actually.)
True , False , and None are reserved words. (2.6 partially enforced the restrictions on None already.)
PEP 3115: New Metaclass Syntax. Instead of:
you must now use:
The module-global __metaclass__ variable is no longer supported. (It was a crutch to make it easier to default to new-style classes without deriving every class from object .)
List comprehensions no longer support the syntactic form [. for var in item1 , item2 , . ] . Use [. for var in ( item1 , item2 , . )] instead. Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a list() constructor, and in particular the loop control variables are no longer leaked into the surrounding scope.
The ellipsis ( . ) can be used as an atomic expression anywhere. (Previously it was only allowed in slices.) Also, it must now be spelled as . . (Previously it could also be spelled as . . . , by a mere accident of the grammar.)
Removed Syntax¶
PEP 3113: Tuple parameter unpacking removed. You can no longer write def foo(a, (b, c)): . . Use def foo(a, b_c): b, c = b_c instead.
Removed backticks (use repr() instead).
Removed <> (use != instead).
Removed keyword: exec() is no longer a keyword; it remains as a function. (Fortunately the function syntax was also accepted in 2.x.) Also note that exec() no longer takes a stream argument; instead of exec(f) you can use exec(f.read()) .
Integer literals no longer support a trailing l or L .
String literals no longer support a leading u or U .
The from module import * syntax is only allowed at the module level, no longer inside functions.
The only acceptable syntax for relative imports is from .[ module ] import name . All import forms not starting with . are interpreted as absolute imports. ( PEP 328)
Classic classes are gone.
Changes Already Present In Python 2.6¶
Since many users presumably make the jump straight from Python 2.5 to Python 3.0, this section reminds the reader of new features that were originally designed for Python 3.0 but that were back-ported to Python 2.6. The corresponding sections in What’s New in Python 2.6 should be consulted for longer descriptions.
PEP 343: The ‘with’ statement . The with statement is now a standard feature and no longer needs to be imported from the __future__ . Also check out Writing Context Managers and The contextlib module .
PEP 366: Explicit Relative Imports From a Main Module . This enhances the usefulness of the -m option when the referenced module lives in a package.
PEP 3101: Advanced String Formatting . Note: the 2.6 description mentions the format() method for both 8-bit and Unicode strings. In 3.0, only the str type (text strings with Unicode support) supports this method; the bytes type does not. The plan is to eventually make this the only API for string formatting, and to start deprecating the % operator in Python 3.1.
PEP 3105: print As a Function . This is now a standard feature and no longer needs to be imported from __future__ . More details were given above.
PEP 3110: Exception-Handling Changes . The except exc as var syntax is now standard and except exc, var is no longer supported. (Of course, the as var part is still optional.)
PEP 3112: Byte Literals . The b". " string literal notation (and its variants like b’. ‘ , b""". """ , and br". " ) now produces a literal of type bytes .
PEP 3116: New I/O Library . The io module is now the standard way of doing file I/O. The built-in open() function is now an alias for io.open() and has additional keyword arguments encoding, errors, newline and closefd. Also note that an invalid mode argument now raises ValueError , not IOError . The binary file object underlying a text file object can be accessed as f.buffer (but beware that the text object maintains a buffer of itself in order to speed up the encoding and decoding operations).
PEP 3118: Revised Buffer Protocol . The old builtin buffer() is now really gone; the new builtin memoryview() provides (mostly) similar functionality.
PEP 3119: Abstract Base Classes . The abc module and the ABCs defined in the collections module plays a somewhat more prominent role in the language now, and built-in collection types like dict and list conform to the collections.MutableMapping and collections.MutableSequence ABCs, respectively.
PEP 3127: Integer Literal Support and Syntax . As mentioned above, the new octal literal notation is the only one supported, and binary literals have been added.
PEP 3141: A Type Hierarchy for Numbers . The numbers module is another new use of ABCs, defining Python’s “numeric tower”. Also note the new fractions module which implements numbers.Rational .
Library Changes¶
Due to time constraints, this document does not exhaustively cover the very extensive changes to the standard library. PEP 3108 is the reference for the major changes to the library. Here’s a capsule review:
Many old modules were removed. Some, like gopherlib (no longer used) and md5 (replaced by hashlib ), were already deprecated by PEP 4. Others were removed as a result of the removal of support for various platforms such as Irix, BeOS and Mac OS 9 (see PEP 11). Some modules were also selected for removal in Python 3.0 due to lack of use or because a better replacement exists. See PEP 3108 for an exhaustive list.
The bsddb3 package was removed because its presence in the core standard library has proved over time to be a particular burden for the core developers due to testing instability and Berkeley DB’s release schedule. However, the package is alive and well, externally maintained at https://www.jcea.es/programacion/pybsddb.htm.
Some modules were renamed because their old name disobeyed PEP 8, or for various other reasons. Here’s the list:
Отличия Python 2.7 и Python 3.6#
В Python 3 строка — это тип str, но, кроме этого, в Python 3 появился тип bytes:
Функция print#
В Python 2.7 print был оператором:
В Python 2.7 можно брать аргументы в скобки, но от этого print не становится функцией и, кроме того, print возвращает другой результат (кортеж):
В Python 3, использование синтаксиса Python 2.7 приведет к ошибке:
input вместо raw_input#
В Python 2.7 для получения информации от пользователя в виде строки использовалась функция raw_input:
В Python 3 используется input:
range вместо xrange#
В Python 2.7 были две функции
range — возвращает список
xrange — возвращает итератор
Пример range и xrange в Python 2.7:
В Python 3 есть только функция range, и она возвращает итератор:
Методы словарей#
Несколько изменений произошло в методах словарей.
dict.keys(), values(), items()#
Методы keys(), values(), items() в Python 3 возвращают «views» вместо списков. Особенность view заключается в том, что они меняются вместе с изменением словаря. И фактически они лишь дают способ посмотреть на соответствующие объекты, но не создают их копию.
Python 2 и 3 — отличия. Функция print
Статья рассказывает, в чём разница между Python 2 и 3. Приводятся сравнительные примеры кода, показываются особенности работы функции print. Даются советы, какую версию выбрать и почему.
О том, что официальная поддержка «Пайтон» 2 скоро прекратится, было объявлено уже давно. Но это не помешало выпустить Python 2.7.18 в апреле 2020 года. Тогда же разработчики утверждали, что это точно последний релиз, поэтому всем рекомендуется переходить на 3-ю версию. Сложно предсказать будущее, но очевидно одно: в противостоянии «Пайтон» 3 vs 2 — более перспективным направлением для развития является именно номер три.
Есть ещё несколько причин остановить свой выбор на «Питоне» 3.x.x: • официальная поддержка сообществом; • более простое изучение (это мнение субъективно, но некоторые его высказывают); • мощнейший инструментарий, множество библиотек; • применимость в машинном обучении и AI, плюс язык используется при обработке больших данных (Big Data).
Главной причиной должно стать то, что «Питон» 2 сегодня является устаревшей версией. Несмотря на это, списывать в утиль его ещё рано: • если вы DevOps-инженер, надо разбираться в конфигурации инструментов управления типа Ansible или Puppet. То есть пригодится умение работать с двумя версиями «Пайтона»; • если большинство проектов в компании реализовано с помощью «Пайтон» 2, знать эту версию тоже необходимо; • если при реализации проекта, требуемые сторонние библиотеки или софт не поддерживаются Python 3, опять же, единственным вариантом остаётся «Пайтон» 2.
Python 2 vs 3
В таблице ниже кратко представлены некоторые отличия и разница версий (2 vs 3):

В результате можно сказать, что языки отличаются следующим: • синтаксис в 3-м «Питоне» проще и понятнее для понимания; • по дефолту, чтобы хранить строки, применяется Unicode, а в Python 2 строковое значение нужно определять посредством «u»; • в третьей ветви языка значения переменных не меняются никогда, а во второй они меняются в случае применения внутреннего цикла for; • в Python 3 исключения помещают в круглые скобки, а в Python 2 они должны быть заключены в notations; • упрощены правила очереди для сравнений; • в Python 3 для итераций есть функция range() , а в Python 2 применяется xrange() .
Модуль future
При разработке 3-й версии «Питона» в язык были включены некоторые ключевые слова и функции, несовместимые с Python 2. Но это не значит, что ими нельзя воспользоваться. Если требуется поддержка Python-кода 3-й версии, можно выполнить импорт, для чего существует встроенный модуль future.
Вот как выглядит импорт функциональности, поддерживающей деление целых чисел:

Прочие детали по модулю future можно посмотреть на странице ниже:

Сравниваем код. Функция print
Лучше всего рассматривать разницу наглядно. Для этого подойдёт простейший код. Начнём с Python 2:
А теперь «Пайтон» 3:
Самое заметное отличие — это изменение синтаксиса print. Используемый ранее оператор print заменили функцией print() . В результате объект вывода надо теперь обязательно заключать в скобки. И если в старом «Питоне» проблемы с дополнительными скобками «in print» отсутствуют, то в новом, в случае вызова print прежним способом, возникнет SyntaxError. Чтобы всё это проверить, совсем необязательно устанавливать у себя сразу два «Пайтона». Можно воспользоваться онлайн-компилятором (можно найти компилятор и для двойки, и для тройки). Есть и другие различия, но они выходят за рамки данной статьи.