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 theunicodetype. - Python 3: Strings are Unicode by default (
str). Byte strings are represented by thebytestype.
- Python 2: Strings are byte sequences by default (
-
printoperator:- Python 2:
printis a statement using a keyword. - Python 3:
printis a function.
# Python 2 print "Hello, World!" # Python 3 print("Hello, World!") - Python 2:
-
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 - Python 2: The
-
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) - Python 2: Syntax
-
range()andxrange()functions:- Python 2:
range()returns a list,xrange()returns a generator (iterator). - Python 3:
range()always returns a generator (iterator),xrange()is removed.
- Python 2:
-
Renaming of some modules: For example,
httplibtohttp.client,urllib2tourllib.requestandurllib.error. -
Changes in dict methods:
dict.iterkeys(),dict.items(), anddict.values():- Python 2: These methods return lists.
- Python 3: These methods return view objects (iterators).
-
New-style classes:
- Python 2: Must explicitly inherit from
objectto create new-style classes. - Python 3: All classes are new-style classes by default (inherit from
objectimplicitly).
- Python 2: Must explicitly inherit from
Many changes in Python 3 aimed to improve consistency, readability, and performance, as well as better Unicode handling.