Sobes.tech
Junior — Middle

How do Python 2 and Python 3 versions differ in functionality and syntax?

sobes.tech AI

Answer from AI

Main differences between Python 2 and Python 3:

  • Print syntax:

    • Python 2: print "Hello" (statement)
    • Python 3: print("Hello") (function)
  • Integer division:

    • Python 2: 5 / 2 returns 2 (integer division)
    • Python 3: 5 / 2 returns 2.5 (float division), for integer division use 5 // 2
  • Unicode:

    • Python 2: strings are byte sequences by default, use u"string" for Unicode
    • Python 3: strings are Unicode by default
  • Iterators:

    • In Python 3, many functions like range(), map(), filter() return iterators instead of lists, saving memory.
  • Exception handling:

    • Python 2: except Exception, e:
    • Python 3: except Exception as e:

Python 3 is the modern version with improvements and fixes, and it is recommended to use it for new projects.