29.10.2014 - General introduction to language, variable types, tuples, lists and dicts.
12.11.2014 - Conditionals, loops, exceptions and functions.
26.11.2014 - Mathematic, datetime, collections.
10.12.2014 - PEP-8 notation, classes.
07.01.2015 - Importing, modules, pip.
21.01.2015 - Django
1990s - Guido Van Rossum
(Benevolent dictator for life)
Basics in C (CPython)
Name comes from Monty Python
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
>>> import this
>>> 3
3
>>> "test"
test
>>>
>>> b
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
b
NameError: name 'b' is not defined
>>> wow so much fun
SyntaxError: invalid syntax
>>> print 3
3
>>> "test"
'test'
>>> print "test"
test
>>> a = 3 # No semicolons needed!
>>> a == 3
True
>>> True == False
False
>>> def foo(x):
if x == 0:
print "That was zero, wasn't it?"
else:
print "Definitely not zero"
>>> foo(3)
Definitely not zero
>>> foo(0)
That was zero, wasn't it?
>>> foo(0)
That was zero, wasn't it?
>>> print 'We don't need a plan'
SyntaxError: invalid syntax
>>> print "We don't need a plan"
We don't need a plan
>>> print ""We don't need a plan" - he said"
SyntaxError: invalid syntax
>>> print """"We don't need a plan" - he said"""
"We don't need a plan" - he said
>>> item = "screen"
>>> print item
screen
>>> type(item)
<type 'str'>
>>> price = 30
>>> type(price)
<type 'int'>
>>> tax = 0.19
>>> type(tax)
<type 'float'>
>>> ...?
>>> print order
computer mouse
>>> ...?
>>> print price
10
>>> tax = 0.19
>>> ...?
>>> print calculated_tax
1.9
>>> price += calculated_tax
>>> print price
...?
>>> type(calculated_tax)
...?
>>> order = "computer mouse"
>>> print order
computer mouse
>>> price = 10
>>> print price
10
>>> tax = 0.19
>>> calculated_tax = price * tax
>>> print calculated_tax
1.9
>>> price += calculated_tax
>>> print price
11.9
>>> type(calculated_tax)
<type 'float'>
>>> type(3)
<type 'int'>
>>> type(3.14)
<type 'float'>
>>> type(2*3.14)
<type 'float'>
>>> type(2/3.14)
<type 'float'>
>>> type(2/3)
<type 'int'>
>>> # ???
>>> 2 / 3
0
>>> 2 / 3.
0.6666666666666666
>>> 2 // 3.
0.0
>>> category = "hardware"
>>> item1 = 'motherboard'
>>> category + item1
'hardwaremotherboard'
>>> category + " - " + item1
'hardware - motherboard'
>>> "%s - %s" % (category, item1)
'hardware - motherboard'
>>> "{0} - {1}".format(category, item1)
'hardware - motherboard'
>>> "{category} - {details}".format(category=category, details=item1)
'hardware - motherboard'
>>> print "line 1\nline2\tafter tab"
line 1
line2 after tab
>>> question_prefix = "What is your"
>>> question1, question2, question3 = "name", "quest",\
"favourite colour"
>>> ...?
What is your name?
What is your quest?
What is your favourite colour?
>>> question_prefix = "What is your"
>>> question1, question2, question3 = "name", "quest",\
"favourite colour"
>>> print "{question_prefix} {0}?\n"\
"{question_prefix} {1}?\n"\
"{question_prefix} {2}?".format(
question1,
question2,
question3,
question_prefix=question_prefix
)
What is your name?
What is your quest?
What is your favourite colour?
>>> orders = []
>>> type(orders)
<type 'list'>
>>> orders = ['coffee', 'milk', 'towels']
>>> print orders
['coffee', 'milk', 'towels']
>>> orders.append('tea')
>>> print orders
['coffee', 'milk', 'towels', 'tea']
>>> orders.extend(['sugar', 'spoons'])
>>> print orders
['coffee', 'milk', 'towels', 'tea', 'sugar', 'spoons']
>>> orders += ['more spoons']
>>> print orders
['coffee', 'milk', 'towels', 'tea', 'sugar', 'spoons', 'more spoons']
>>> orders.remove('towels')
>>> print orders
['coffee', 'milk', 'tea', 'sugar', 'spoons', 'more spoons']
>>> orders = orders[0:3]
>>> print orders
['coffee', 'milk', 'tea']
>>> random_stuff = ['test', 1, 3.14, ['name', 'quest'], orders]
>>> print random_stuff
['test', 1, 3.14, ['name', 'quest'], ['coffee', 'milk', 'tea']]
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[3]
4
>>> numbers[2:5]
[3, 4, 5]
>>> numbers[:4]
[1, 2, 3, 4]
>>> numbers[-3:]
[8, 9, 10]
>>> numbers[::3]
[1, 4, 7, 10]
>>> numbers[3:1]
[]
>>> numbers[1:-3:2]
[2, 4, 6]
>>> numbers[::-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> seq[:] # [seq[0], seq[1], ..., seq[-1] ]
>>> seq[low:] # [seq[low], seq[low+1], ..., seq[-1] ]
>>> seq[:high] # [seq[0], seq[1], ..., seq[high-1]]
>>> seq[low:high] # [seq[low], seq[low+1], ..., seq[high-1]]
>>> seq[::stride] # [seq[0], seq[stride], ..., seq[-1] ]
>>> seq[low::stride] # [seq[low], seq[low+stride], ..., seq[-1] ]
>>> seq[:high:stride] # [seq[0], seq[stride], ..., seq[high-1]]
>>> seq[low:high:stride] # [seq[low], seq[low+stride], ..., seq[high-1]]
>>> print numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> ...?
[4, 7]
>>> ...?
[10, 8, 6, 4, 2]
>>> ...?
[6, 5, 4]
>>> ...?
[7, 4]
>>> print numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[3:8:3]
[4, 7]
>>> numbers[::-2]
[10, 8, 6, 4, 2]
>>> numbers[5:2:-1]
[6, 5, 4]
>>> numbers[6:2:-3]
[7, 4]
>>> name = "Grand Parade"
>>> name[-2]
'd'
>>> name[-2] = 't'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> name[:-2] + 'chut' + name[-1:]
'Grand Parachute'
>>> name.replace('Grand', 'Enormous')
'Enormous Parade'
>>> name.index('a')
2
>>> name[::-1]
'edaraP dnarG'
>>> "and" in name
True
>>> type(True)
<type 'bool'>
>>> not False
True
>>> a = None
>>> type(a)
<type 'NoneType'>
>>> bool(a)
False
>>> bool("")
False
>>> bool([])
False
>>> bool([""])
True
>>> bool([None])
True
>>> True, False = False, True
>>> True
False
>>> point = (1, 3)
>>> len(point)
2
>>> min(point)
1
>>> point[0] += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> point.append(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
>>> order = {'name': 'screen', 'price': 20}
>>> order['name']
'screen'
>>> order['approving']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'approving'
>>> order['approving'] = ('manager1', 'manager2')
>>> order
{'price': 20, 'name': 'screen', 'approving': ('manager1', 'manager2')}
>>> order['approving'] = (
{'name': 'manager1', 'approved': False},
{'name': 'manager2', 'approved': True}
)
>>> from pprint import pprint
>>> pprint(order)
{'approving': ({'approved': False, 'name': 'manager1'},
{'approved': True, 'name': 'manager2'}),
'name': 'screen',
'price': 20}
>>> del order['approving']
>>> order
{'price': 20, 'name': 'screen'}
>>> order.keys()
['price', 'name']
>>> order.values()
[20, 'screen']
>>> order.items()
[('price', 20), ('name', 'screen')]
>>> dict([('price', 20), ('name', 'screen')])
{'price': 20, 'name': 'screen'}
>>> 'price' in order
True
>>> 'screen' in order
False
>>> order.update({'price': 10, 'bonus': '-50%'})
>>> order
{'bonus': '-50%', 'price': 10, 'name': 'screen'}
>>> order.get('bonus')
'-50%'
>>> order.get('ordering')
>>> order.get('ordering', 'Undefined')
'Undefined'
>>> a = {}
>>> a[1] = 'test'
>>> a[(1, 3)] = 'stranger test'
>>> a[True] = 'even stranger test'
>>> a[{'foo': 'bar'}] = 'this is madness'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> a
{1: 'even stranger test', (1, 3): 'stranger test'}
>>> a[True]
'even stranger test'
>>> ...?
>>> print "Ordered {item} from {shop} for {price}$".format(**order) + \
'\nMust be approved by: ' + \
', '.join(order.get('approving', ['unspecified']))
Ordered screen from Hardware Store for 20$
Must be approved by: manager1, manager2, manager3
>>> order = {
'item': 'screen',
'price': 20,
'shop': 'Hardware Store',
'approving': (
'manager1',
'manager2',
'manager3'
)
}
>>> print "Ordered {item} from {shop} for {price}$".format(**order) + \
'\nMust be approved by: ' + \
', '.join(order.get('approving', ['unspecified']))
Ordered screen from Hardware Store for 20$
Must be approved by: manager1, manager2, manager3
>>> print "".join(["list", "of", "separate", "words"])
listofseparatewords
>>> print " ".join(["list", "of", "separate", "words"])
list of separate words
>>> print "ea ".join(["list", "of", "separate", "words"])
listea ofea separateea words
>>> "4, 8, 15, 16, 23, 42".split()
['4,', '8,', '15,', '16,', '23,', '42']
>>> "4, 8, 15, 16, 23, 42".split(', ')
['4', '8', '15', '16', '23', '42']
>>> map(int, "4, 8, 15, 16, 23, 42".split(', '))
[4, 8, 15, 16, 23, 42]
>>> sum(map(int, "4, 8, 15, 16, 23, 42".split(', ')))
108
>>> a, b = [0], [0]
>>> a[0], b[0] = b, a
>>> a
[[[...]]]
>>> b
[[[...]]]
>>> a in b
True
>>> a == b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: maximum recursion depth exceeded in cmp
>>> a == b[0]
True
Questions?