Python 3 - Examples

Updated: 2018-06-27

enumerate

for i in range(len(flavor_list)):
    flavor = flavor_list[i]
    print('%d: %s' % (i + 1, flavor))

for i, flavor in enumerate(flavor_list):
    print('%d: %s' % (i + 1, flavor))

Download pages from wikipedia

import urllib2
opener = urllib2.build_opener()
opener.addheaders =[('User-agent','Mozilla/5.0')]
infile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes')
page = infile.read()

fib

def fibonacci():
    a, b = 0, 1
    while True:
        yield b
        a, b = b, a + b

reverse

def reverse(data):
    for index in range(len(data)-1, -1, -1):
        yield data[index]

use for ... in ...

>>> list(reversed('golf'))
['f', 'l', 'o', 'g']
class Reverse:
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def next(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]
>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
>>> for char in rev:
...     print char
...
m
a
p
s

HTTP Server

Start HTTP server

Python 2.x:

$ python -mSimpleHTTPServer 8080

Python 3.x:

$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 ...