Tutorial by Examples

In Python 2, print is a statement: Python 2.x2.7 print "Hello World" print # print a newline print "No newline", # add trailing comma to remove newline print >>sys.stderr, "Error" # print to stderr print("hello"...
Python 2.x2.7 In Python 2 there are two variants of string: those made of bytes with type (str) and those made of text with type (unicode). In Python 2, an object of type str is always a byte sequence, but is commonly used for both text and binary data. A string literal is interpreted as a byte s...
The standard division symbol (/) operates differently in Python 3 and Python 2 when applied to integers. When dividing an integer by another integer in Python 3, the division operation x / y represents a true division (uses __truediv__ method) and produces a floating point result. Meanwhile, the ...
In Python 2, reduce is available either as a built-in function or from the functools package (version 2.6 onwards), whereas in Python 3 reduce is available only from functools. However the syntax for reduce in both Python2 and Python3 is the same and is reduce(function_to_reduce, list_to_reduce). A...
In Python 2, range function returns a list while xrange creates a special xrange object, which is an immutable sequence, which unlike other built-in sequence types, doesn't support slicing and has neither index nor count methods: Python 2.x2.3 print(range(1, 10)) # Out: [1, 2, 3, 4, 5, 6, 7, 8, 9...
Python 3.x3.0 In Python 3, you can unpack an iterable without knowing the exact number of items in it, and even have a variable hold the end of the iterable. For that, you provide a variable that may collect a list of values. This is done by placing an asterisk before the name. For example, unpacki...
This is the Python 2 syntax, note the commas , on the raise and except lines: Python 2.x2.3 try: raise IOError, "input/output error" except IOError, exc: print exc In Python 3, the , syntax is dropped and replaced by parenthesis and the as keyword: try: raise IOErro...
In Python 2, an iterator can be traversed by using a method called next on the iterator itself: Python 2.x2.3 g = (i for i in range(0, 3)) g.next() # Yields 0 g.next() # Yields 1 g.next() # Yields 2 In Python 3 the .next method has been renamed to .__next__, acknowledging its “magic” ro...
Python 2.x2.3 Objects of different types can be compared. The results are arbitrary, but consistent. They are ordered such that None is less than anything else, numeric types are smaller than non-numeric types, and everything else is ordered lexicographically by type. Thus, an int is less than a st...
In Python 2, user input is accepted using the raw_input function, Python 2.x2.3 user_input = raw_input() While in Python 3 user input is accepted using the input function. Python 3.x3.0 user_input = input() In Python 2, the input function will accept input and interpret it. While this ...
In Python 3, many of the dictionary methods are quite different in behaviour from Python 2, and many were removed as well: has_key, iter* and view* are gone. Instead of d.has_key(key), which had been long deprecated, one must now use key in d. In Python 2, dictionary methods keys, values and items ...
In Python 2, exec is a statement, with special syntax: exec code [in globals[, locals]]. In Python 3 exec is now a function: exec(code, [, globals[, locals]]), and the Python 2 syntax will raise a SyntaxError. As print was changed from statement into a function, a __future__ import was also added. ...
In Python 2, when a property raise a error, hasattr will ignore this property, returning False. class A(object): @property def get(self): raise IOError class B(object): @property def get(self): return 'get in b' a = A() b = B() print 'a hasattr get:...
A few modules in the standard library have been renamed: Old nameNew name_winregwinregConfigParserconfigparsercopy_regcopyregQueuequeueSocketServersocketserver_markupbasemarkupbasereprreprlibtest.test_supporttest.supportTkintertkintertkFileDialogtkinter.filedialogurllib / urllib2urllib, urllib.pars...
In Python 2, an octal literal could be defined as >>> 0755 # only Python 2 To ensure cross-compatibility, use 0o755 # both Python 2 and Python 3
In Python 3.x all classes are new-style classes; when defining a new class python implicitly makes it inherit from object. As such, specifying object in a class definition is a completely optional: Python 3.x3.0 class X: pass class Y(object): pass Both of these classes now contain object in ...
In Python 2, <> is a synonym for !=; likewise, `foo` is a synonym for repr(foo). Python 2.x2.7 >>> 1 <> 2 True >>> 1 <> 1 False >>> foo = 'hello world' >>> repr(foo) "'hello world'" >>> `foo` "'hello world'"...
Python 2.x2.7 "1deadbeef3".decode('hex') # Out: '\x1d\xea\xdb\xee\xf3' '\x1d\xea\xdb\xee\xf3'.encode('hex') # Out: 1deadbeef3 Python 3.x3.0 "1deadbeef3".decode('hex') # Traceback (most recent call last): # File "<stdin>", line 1, in <module> ...
In Python 3 the cmp built-in function was removed, together with the __cmp__ special method. From the documentation: 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 compariso...
Python 2.x2.3 x = 'hello world!' vowels = [x for x in 'AEIOU'] print (vowels) # Out: ['A', 'E', 'I', 'O', 'U'] print(x) # Out: 'U' Python 3.x3.0 x = 'hello world!' vowels = [x for x in 'AEIOU'] print (vowels) # Out: ['A', 'E', 'I', 'O', 'U'] print(x) # Out: 'hello world!' ...

Page 1 of 2