python2 vs python3



Python 2 and Python 3 are two major versions of the Python programming language. Python 3 was introduced as an improvement and a successor to Python 2, addressing some of its limitations and introducing new features. As of my last knowledge update in January 2022, it's important to note that Python 2 has reached its end of life, and developers are strongly encouraged to use Python 3 for all new projects. Here are some key differences between Python 2 and Python 3:


1. Print Statement:

   - Python 2: `print` is a statement (e.g., `print "Hello, World!"`).

   - Python 3: `print()` is a function and requires parentheses (e.g., `print("Hello, World!")`).


2. Division:

   - Python 2: Division of two integers performs integer division by default (e.g., `5/2` results in `2`).

   - Python 3: Division of two integers results in float division by default (e.g., `5/2` results in `2.5`). To perform integer division, you can use the `//` operator.


3. Unicode Support:

   - Python 2: Strings are ASCII by default, and Unicode support requires a `u` prefix (e.g., `u"Hello"`).

   - Python 3: Strings are Unicode by default.


4. Range vs. xrange:

   - Python 2: `range()` produces a list, and `xrange()` produces an iterator.

   - Python 3: `range()` now behaves like Python 2's `xrange()`, and there is no `xrange()` in Python 3.


5. Input Function:

   - Python 2: `input()` evaluates user input as code, and `raw_input()` is used for getting string input.

   - Python 3: `input()` returns a string, and `raw_input()` is no longer present.


6. Error Handling:

   - Python 2: `except` syntax uses a comma (e.g., `except IOError, e:`).

   - Python 3: `as` is used for exception handling (e.g., `except IOError as e:`).


7. Byte Literals:

   - Python 2: No dedicated byte literal.

   - Python 3: Introduced a dedicated `b` prefix for byte literals (e.g., `b'hello'`).


8. String Formatting:

   - Python 2: `%` formatting is commonly used.

   - Python 3: `format()` method and f-strings (formatted string literals) are recommended.


9. Iterating Over Dictionaries:

   - Python 2: `dict.keys()`, `dict.values()`, and `dict.items()` return lists.

   - Python 3: These methods return views, and if you need lists, you can use `list(dict.keys())`, `list(dict.values())`, and `list(dict.items())`.


As mentioned earlier, Python 2 is no longer maintained, and developers are encouraged to migrate to Python 3 for ongoing and future projects. The information provided here is based on the state of Python as of my last update in January 2022, and there may have been further developments or changes since then.


Comments