Python 3 was released in Dec 2008 – almost 10 years and we still found a lot of python 2.7 developers. Python 3 is Not backward compatible with Python 2. Most language features are the same, some detail has changed and many deprecated features have been tided up and removed

The main reason today to work with python 2.7 is to keep maintain a big project written in python 2. If you start a new project you definitely choose python 3.

It is not hard to port python 2 code to python 3 – you can do it manually or use the utility 2to3.py.

The Print Function

The first thing everyone notices about Python 3 is that the print statement is no longer a, um, statement: it is a built-in function. The effect is that we now have to put parentheses around the thing we wish to print.

Most commonly used for displaying a comma separated list (Objects are stringified)

1

2

3

4

5

ls=[1,2,3]

print('hello',10,ls)

# prints:

# hello 10 [1, 2, 3]

Has several named arguments

end= characters to be appended, default is ‘\n’ (newline)

file= file object to be written to, default is sys.stdout

sep= separator used between list items, default is a single space

1

2

3

4

5

6

ls=[1,2,3]

print('hello',10,ls,sep=' $ ',end=':')

print('bye')

# prints:

# hello $ 10 $ [1, 2, 3]:bye

Also format changed but you can use the old format (using %)

Simple keyboard (stdin) input

raw_input is replaced by input. The input statement reads from stdin, which is usually the keyboard but may have been redirected

1

2

3

4

5

num=input("enter number")

print("res",int(num)+100)

# enter number:33

# res: 133

Misc Changes

The tests <> and cmp are no longer supported – both statements throws errors – use ==, !=

1

2

3

4

5

ifx<>y:

print("ok")

ifcmp(x,y):

print("ok")

Non Ascii Names are allowed – use magic comment for that

1

2

3

4

5

# coding=iso-8859-8

משתנה='hello'

print(משתנה)

Backticks are removed – use repr instead

1

2

3

4

5

6

7

8

9

10

11

d=10

r='2'

print(d+r)

#TypeError: unsupported operand type(s) for +: 'int' and 'str'

print(`d`+r)

# SyntaxError: invalid syntax (was ok in python 2)

print(repr(d)+r)

# 102

New format for octal numbers:

1

num=0o127

Trailing L is no longer used – ints and long are the same

True, False, None are now keywords (In Python 2 they could be redefined)

Strings in python 3

Multi-byte characters

\unnnn – two-byte Unicode character

\Unnnnnnnn – four-byte Unicode character

\N{name} – a named Unicode character

The old Python 2 u”…” prefix is no longer supported

1

2

3

4

5

6

7

euro="\u20ac"

print(euro)

euro="\N{euro sign}"

print(euro)

# €

# €

bytes() and bytearray()

used for low level interfacing, convert to string using decode:

1

2

cb=b"simple single-byte string"

print(cb.decode())

Opening a file in binary mode returns a bytes object. Convert from a string using string.encode()