Hi and Enjoy

Plan

  • 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

Hour of work

~45 minutes of work

Today

  • General introduction
  • IDLE
  • Syntax
  • Numbers
  • Strings
  • Lists
  • More strings
  • Tuples
  • Dicts

General Introduction

1990s - Guido Van Rossum

(Benevolent dictator for life)

Basics in C (CPython)

Name comes from Monty Python

Philosophy

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.

Philosophy

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!

Philosophy

>>> import this

IDLE

>>> 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

>>> print 3
3
>>> "test"
'test'
>>> print "test"
test

syntax

>>> 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?

syntax

>>> 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

variables

>>> item = "screen"
>>> print item
screen
>>> type(item)
<type 'str'>
>>> price = 30
>>> type(price)
<type 'int'>
>>> tax = 0.19
>>> type(tax)
<type 'float'>

exercise

>>> ...?
>>> print order
computer mouse
>>> ...?
>>> print price
10
>>> tax = 0.19
>>> ...?
>>> print calculated_tax
1.9
>>> price += calculated_tax
>>> print price
...?
>>> type(calculated_tax)
...?

solution

>>> 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'>

numbers

>>> 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

strings

>>> 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

exercise

>>> 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?

solution

 

>>> 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?

lists []

>>> 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']

lists []

>>> 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']]

slicing

>>> 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]

slicing

>>> 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]]

exercise

>>> print numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> ...?
[4, 7]
>>> ...?
[10, 8, 6, 4, 2]
>>> ...?
[6, 5, 4]
>>> ...?
[7, 4]

solution

>>> 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]

more strings

>>> 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

booleans and None

>>> 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

tuples ()

(immutable lists)

>>> 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'

dicts {}

>>> 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')}

dicts {}

>>> 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'}

keys, values

>>> 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

dicts {}

>>> 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'

possible keys

>>> 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'

another wat

>>> a
{1: 'even stranger test', (1, 3): 'stranger test'}
>>> a[True]
'even stranger test'

exercise

>>> ...?
>>> 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

solution

>>> 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

join, split

>>> 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

join, split

>>> "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

One more wat?

wat #3

>>> 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

Thanks

Questions?

Made with Slides.com