Sobes.tech
Junior

What are the main differences between Python 2 and Python 3?

sobes.tech AI

Answer from AI

Main differences between Python 2 and Python 3:

  • String handling:

    • Python 2: Strings are byte sequences by default (str). Unicode is represented by the unicode type.
    • Python 3: Strings are Unicode by default (str). Byte strings are represented by the bytes type.
  • print operator:

    • Python 2: print is a statement using a keyword.
    • Python 3: print is a function.
    # Python 2
    print "Hello, World!"
    
    # Python 3
    print("Hello, World!")
    
  • Integer division:

    • Python 2: The / operator performs integer division between integers.
    • Python 3: The / operator performs true division, returning a float. For integer division, use //.
    # Python 2
    print 5 / 2  # Outputs 2
    
    # Python 3
    print(5 / 2)  # Outputs 2.5
    print(5 // 2) # Outputs 2
    
  • Exceptions:

    • Python 2: Syntax except exc, var:.
    • Python 3: Syntax except exc as var:.
    # Python 2
    try:
        # Code that may raise an exception
        pass
    except ValueError, e:
        print e
    
    # Python 3
    try:
        # Code that may raise an exception
        pass
    except ValueError as e:
        print(e)
    
  • range() and xrange() functions:

    • Python 2: range() returns a list, xrange() returns a generator (iterator).
    • Python 3: range() always returns a generator (iterator), xrange() is removed.
  • Renaming of some modules: For example, httplib to http.client, urllib2 to urllib.request and urllib.error.

  • Changes in dict methods: dict.iterkeys(), dict.items(), and dict.values():

    • Python 2: These methods return lists.
    • Python 3: These methods return view objects (iterators).
  • New-style classes:

    • Python 2: Must explicitly inherit from object to create new-style classes.
    • Python 3: All classes are new-style classes by default (inherit from object implicitly).

Many changes in Python 3 aimed to improve consistency, readability, and performance, as well as better Unicode handling.

What are the main differences between Python 2 and… - sobes.tech