Python Lecture 5
Python Lecture 5
• New:
print("foo", "bar", "baz")
print statement (3)
• Old:
print "foobar", # no newline
• New:
print("foobar", end="")
print("foobar", end=" ")
# space instead of newline
print statement (4)
• Old:
>>> print "There are <", 2**32, "> possibilities!"
• New:
>>> print("There are <", 2**32, "> possibilities!",
sep="") # no separator
• New:
>>> print()
print statement (6)
• Old:
>>> print >> sys.stderr, "error!"
• New:
>>> print("error!", file=sys.stderr)
String formatting (1)
• Old:
>>> "int: %d\tfloat: %f\tstring: %s\n" %
• New:
>>> "int: {0}\tfloat: {1}\tstring: {2}\n".format(
'a: 1 b: 2 c: 3'
'Braces: {}'
String formatting (3)
• Attributes inside curly braces:
>>> lst = [1, 2, 3, 4, 5]
'lst[3] = 4'
'dict["foo"] = 1'
String formatting (4)
• Dot syntax inside curly braces:
>>> import string
string)
• Format specifiers:
>>> "pi: {0:15.8f}".format(math.pi)
'pi: 3.14159265'
Iterators (1)
• Iterators are a new kind of Python object
• Have been around for a while (since Python 2.2)
• Are used more extensively in Python 3.x
• Embody the notion of "sequence that you can take
the next item of"
Iterators (2)
• Iterators can be constructed from most Python
sequences using the iter() function:
>>> i = iter(range(10))
>>> i
>>> i.__next__()
>>> i.__next__()
...
Iterators (4)
• Continuing:
>>> i.__next__()
>>> i.__next__()
>>> i.__next__()
StopIteration
Iterators (5)
• Iterating through an iterator:
i = iter(range(5))
for item in i:
print(item)
4
Iterators (6)
• In Python 3.x, common functions like map() and
filter() return iterators, not lists
• However, you can turn an iterator into a list using
the list() built-in function
• Advantage of iterator: doesn't have to generate the
entire list all at once
The range() function
• The range() function no longer returns a list
• Instead, it's "lazy"; it evaluates its arguments as
they are needed (sort of like an iterator)
• Useful if you write e.g. range(1000000) and only
use the first (say) 1000 elements
• This is also doable in Python 2.x as the xrange()
function, which no longer exists in Python 3.x
Integer division
• Dividing two integers that don't divide evenly
returns a float:
1 / 2 # ==> 0.5
5 / 3 # ==> 1.66666...
• Binary literals
• Use 0b prefix (by analogy with 0x for hexadecimal)
•
0b11001 # ==> 25
{1, 2}
• X in <set>
•
>>> 1 in {1, 2, 3}
•
True
Syntax changes (3)
• Set comprehensions:
•
for y in range(3)}
•
{0, 1, 2, 3, 4}
• Note difference between this and corresponding
list comprehension: no duplicates!
•
for y in range(3)]
•
[0, 1, 2, 1, 2, 3, 2, 3, 4]
Syntax changes (4)
• Dictionary comprehensions
•
b'foo'
•
>>> bytes([102,111,111])
•
b'foo'
Syntax changes (6)
• Byte arrays can also have characters outside of
ASCII range:
•
>>> bytes([127,128,129])
•
b'\x7f\x80\x81'
•
>>> bytes([255,255,256])
•
... return x + y
•
>>> foo(3, 4)
•
7
•
>>> print(foo.__annotations__)
•
def adder(x):
•
def add(y):
•
return x + y
•
return add
•
>>> add5(10) # 15
• So far so good ...
Syntax changes (10)
• Sometimes want to modify variable in an outer
scope:
•
def counter(x):
•
count = x
•
def increment():
•
nonlocal count
•
count += 1
•
return count
•
return increment
•
>>> c = counter(0)
•
>>> c() # 1
Syntax changes (11)
• Iterable unpacking:
•
>>> a
•
0
•
>>> c
•
4
•
>>> b
•
[1, 2, 3]
Built-in functions
• raw_input() is now just input()
• reduce() is now functools.reduce()
• dict.has_key() gone; use x in dict
Exceptions
• All exceptions must subclass from
BaseException
@foo
•
def bar(x):
•
def bar(x):
•
class Foo:
•
@staticmethod
•
return 2 * x
•
>>> Foo.bar(10)
•
20
• bar is a method of class Foo, not of Foo instances
• though it also works on instances
Summing up
• These changes remove language "warts", make
language cleaner and more consistent
• Many more extensions/changes than I've
discussed here!
• See online docs for comprehensive list
• Will take time to absorb all the changes
• Python 3.x provides "2to3" program to automate
most conversions