Introduction to Python

Created by Ian Connolly for DUCSS / Slides available on GitHub

What Is Python?

  • General-purpose
  • Emphasises clarity and readability
  • Multi-paradigm
  • Dynamically typed

Versioning

  • Two main versions: 2.7.x and 3.x
  • We'll be using 2.7.x
  • Don't worry about the difference for now

Hello, world!


print "Hello, world!"

It's that easy!

Installing Python

Already installed on OS X and Linux

Windows people can get it from python.org

OS X people should use Homebrew to get an up-to-date version

Both DUCSS and Netsoc servers have it installed

Running Python

Open a terminal/cmd window and type "python"

This is a Python Read-Eval-Print Loop (REPL)

Really useful for interactive programming

Some math...


4 + 4 # 8
9 - 5 # 4
10 * 5 # 50
9 / 5 # 1
9.0 / 5.0 # 1.8

a = 4
b = 5
a - b # -1

Nothing too hairy yet!

While we're commenting...


4 + 4 # I'm an inline comment

'''
I'm a block comment!
'''

Truthiness


True # True
False # False

bool(1) # True
bool(0) # False
bool("") # False
bool("not an empty string") # True

Truthiness pt. 2


a = 4
b = 5

a == 4 # True
a == b # False
a != b # True
a < b # True
a > b # False
b <= 5 # True
a >= 3 # True

Truthiness pt.3


if a == 4:
    print "a is 4!"
elif a == 5: 
    print "a is 5!"
else:
    print "a isn't 4 or 5!"

Okay WHOA, what did we just do there?

Blocks o' code

In Python, we delimit blocks of code with indentation

Python style guide says to use 4 spaces

You can use tabs too (Please don't)

Never, ever, ever, ever mix tabs and spaces in the same file


if a == 4:
    print "a is 4!"

Loopy blocks


while True:
    print "Looping forever!"

i = 0
while i < 10:
    print i
    i = i + 1

Functions


def my_function():
    print "You called my function!"

my_function() # You called my function!

Classes, Objects and Methods


class MyClass(object):

    def my_method(self):
        print "you called my method!"

myobject = MyClass()
myobject.my_method() # you called my method!

More on these later...

Lists


a = ['spam', 'eggs', 100, 1234]
a[0] # 'spam'
a[-2] # 100

a[2] = a[2] + 23 # 123
a # ['spam', 'eggs', 123, 1234]

len(a) # 4

a[:2] # ['spam', 'eggs']

More Lists


a = [5] # [5]
a.append(6) # a is [5, 6]
a.extend([7, 5, 6]) # a is [5, 6, 7, 5, 6]
a.count(5) # 2
a.reverse() # a is [6, 5, 7, 6, 5]
a.pop(6) # IndexError, a[6] does not exist
a.remove(6) # a is [5, 7, 6, 5]
5 in a # True
10 not in a # True
min(a) # 5
max(a) # 7

Lists are mutable

Adding, deleting, reordering etc. affects the original list. Not a copy

Loopy lists


a = [3, 4, 5, 6]
for item in a:
    print item 

a = [3, 4, 5, 6]
for index, item in enumerate(a):
    print "Index is: {} and item is: {}".format(index, item)

Strings


name = "taylorswift"
name.capitalize() # "Taylorswift"
name # "taylorswift"

Strings are immutable

All String methods return a copy of the string, the original is unchanged

Lots of cool methods for checking, manipulating and splitting strings

We can slice strings too


name[:4] # "tayl"

Dictionaries

Key -> Value pairs


sprangbreak = {"selena":"gomez", "vanessa":"hudgens"}
sprangbreak["selena"] # "gomez"
"selena" in sprangbreak # True
"james" in sprangbreak # False
sprangbreak["james"] = "franco"
"james" in sprangbreak # True
sprangbreak[9] = True
sprangbreak # {"selena":"gomez", "vanessa":"hudgens", "james":"franco", 9:True}

Iterating dictionaries

Iterate a copy


for key in sprangbreak.keys():
    print key

for value in sprangbreak.values():
    print value

for key, value in sprangbreak.items():
    print key, value

Iterate the real thing


for key in sprangbreak.iterkeys():
    print key

for value in sprangbreak.itervalues():
    print value

for key, value in sprangbreak.iteritems():
    print key, value

Careful now, Ted.

Tuples

Immutable data structure


a = (1.5, 2.7)

x, y = a
x # 1.5
y # 2.7

Functions pt.2


def my_function(a, b):
    return a + b

my_function(3, 4) # 7
my_function("Hel", "lo") # "Hello"

def my_function(a, b=4):
    return a + b

my_function(3) # 7
my_function("Hel") # TypeError: cannot concatenate 'str' and 'int' objects
my_function("Hel", "lo") # "Hello"

Importing


import math
math.sqrt(9) # 3.0

import math as maths
maths.sqrt(9) # 3.0

from math import sqrt
sqrt(9) # 3.0

from math import sqrt as root
root(9) # 3.0

Classes, Objects and Methods pt. 2


class MyClass(object):
    pass    # 'pass' tells Python that this is an empty block

a = MyClass()
a.x = 5
a.y = 4
a.z = a.x + a.y # 9

Yep, you can add to objects at runtime

Classes, Objects and Methods pt. 3


import math 

class Point(object):

    def __init__(self, in_x, in_y):
        self.x = in_x
        self.y = in_y

    def distance_to(self, other_point):
        x_frag = math.pow(other_point.x - self.x, 2)
        y_frag = math.pow(other_point.y - self.y, 2)
        return math.sqrt(x_frag + y_frag)

    def __str__(self):
        return "({}, {})".format(x_frag, y_frag)

a = Point(0.0, 0.0)
b = Point(1.0, 1.0)
print a # (0.0, 0.0)
a.distance_to(b) # 1.41421...

Pop quiz: What happens?


a = Point(True, False)
b = Point("Mean", "Girls")
print a
a.distance_to(b)

Duck typing means errors can pop up later than expected!

How could we alter our code to make it turn up earlier?

Yer a wizard now, 'Arry

Stuff like... __str__() and __init__() are magic

We inherit them from object

As you explore Python you'll see their uses

Functions pt. 3

So we've seen how to pass parameters to functions


def my_function(a, b):
    return a + b

my_function(3, 4) # 7
my_function("Hel", "lo") # Hello

We've passed ints, and strings, and 'self'...

What about another function?


def add(a, b):
    return a + b

def my_function(a, b, in_function):
    return in_function(a, b)

my_function(3, 4, add) # 7

JavaScript-y types will notice this allows a callback pattern

Comprende?

Back to our collections!

We've created lists and dictionaries like this:


a = ["this", "is", "a", "list"]
b = {"this": "is", "a": "dictionary"}

We could also use their constructors explicitly like this:


a = list("this", "is", "a", "list")
b = dict(this="is", a="dictionary"}

But what if we don't know when we're coding what we're putting in the collection?

Comprehensions!


a = [x for x in iterable]
b = {x:y for (x, y) in iterable}

More comprehensions!

Let's see what we'd actually use these for

A list of the first 10 numbers


[i for i in range(10)]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

A dictionary of the first 10 numbers and their squares?


{i: i*i for i in range(10)}

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

We can also filter what we take from the iterable...


[i for i in range(100) if i % 2 == 0]

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]

Running Python pt.2

Typing "python my_file.py" will run my_file

Python will run the file, top to bottom.

By convention, as little as possible code is put at the top-level

We use a bit of 'magic' to simulate C/C++/Java main function


def main():
    print "I am the main function"

if __name__ == "__main__":
    main()

What can I do with this?

  • Modern, dynamic web applications with Flask/Django
  • Games programming with PyGame
  • Desktop applications programming with PyGTK
  • Scientific programming with NumPy, SciPy and iPython
  • Your assignments!

What next?

Introduction to Flask. Date TBA

Python Ireland

Fork the DUCSS site and hack away!

DUCSS in 4th Week

Questions?