Features ONLY in Python 3
Features added in Python 2.7 (since we have been using Python 2.6)
s1 = "abc¥"
data = s1.encode()
# These are encoded as bytes
print(data)
b'abc\xc2\xa5'
# Iteration does not give text characters like string.
for x in data:
print(x)
97 98 99 194 165
# Decode to get text representation
data.decode()
'abc¥'
# Interface is same as string - string methods work
data.capitalize()
b'Abc\xc2\xa5'
# Already can do this
a,b,c = [1, 'cool', True]
print(a)
print(b)
print(c)
1 cool True
# Now you can do
a,b,*c = [1, 'cool', True, 'more']
print(a)
print(b)
print(c)
1 cool [True, 'more']
def weird(a,b,c=False):
if c:
print("I have deleted everything")
else:
print("No damage done yet")
# Passed True by mistake. Didnt know anything about the keyword arg 'c'
weird(1,2,True)
I have deleted everything
def nice_weird(a,b,*k, c=False):
if c:
print("I have deleted everything")
else:
print("No damage done yet")
nice_weird(1,2,True)
No damage done yet
nice_weird(1,2,True,False,True,c=False)
No damage done yet
raise NotImplementedError from OSError
my_range = range(0,5)
type(my_range)
range
for x in range(0,5):
print(x)
0 1 2 3 4
list(my_range)
[0, 1, 2, 3, 4]
mymap = map(lambda x: x**2, [3,4,5])
type(mymap)
map
list(mymap)
[9, 16, 25]
# Incorrect
raise IOError, "got error"
File "<ipython-input-1-f0429c1e574a>", line 2 raise IOError, "got error" ^ SyntaxError: invalid syntax
# Correct
raise IOError("got error")
--------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-2-a79d4b26992b> in <module>() 1 # Correct ----> 2 raise IOError("got error") OSError: got error
# Incorrect
try:
pass
except IOError, err:
pass
File "<ipython-input-4-b44e006b740d>", line 4 except IOError, err: ^ SyntaxError: invalid syntax
# Correct:
try:
pass
except IOError as err:
pass
[1,2,3] > "hello"
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-30-820d7f4db400> in <module>() ----> 1 [1,2,3] > "hello" TypeError: unorderable types: list() > str()
# Generator
def gen():
for i in [0,1,2]:
yield i
# To pass on values from generator you have to do this
def process_gen():
for j in gen():
yield j
list(process_gen())
[0, 1, 2]
# Now you can do this
def process_gen_new():
yield from gen()
list(process_gen_new())
[0, 1, 2]
from enum import Enum
class Shape(Enum):
circle = 0
square = 1
rhombus = 2
print(Shape.circle)
print(Shape.circle.name)
print(Shape.circle.value)
Shape.circle circle 0
mydict = {Shape.circle:"circular", Shape.square:"squarish"}
print(mydict[Shape.circle])
circular
def masquerader(a:int, b:str) -> float:
print("I am a Haskell/Ocaml/Scala wannabe")
masquerader("doesnt", "matter")
I am a Haskell/Ocaml/Scala wannabe
from IPython.display import HTML
HTML('<iframe src=https://python3wos.appspot.com/ width=700 height=350></iframe>')