Created by Ian Connolly for DUCSS / Slides available on GitHub
print "Hello, world!"
It's that easy!
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
Open a terminal/cmd window and type "python"
This is a Python Read-Eval-Print Loop (REPL)
Really useful for interactive programming
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!
4 + 4 # I'm an inline comment
'''
I'm a block comment!
'''
True # True
False # False
bool(1) # True
bool(0) # False
bool("") # False
bool("not an empty string") # True
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
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?
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!"
while True:
print "Looping forever!"
i = 0
while i < 10:
print i
i = i + 1
def my_function():
print "You called my function!"
my_function() # You called my function!
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...
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']
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
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)
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"
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}
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.
Immutable data structure
a = (1.5, 2.7)
x, y = a
x # 1.5
y # 2.7
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"
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
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
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...
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?
Stuff like... __str__() and __init__() are magic
We inherit them from object
As you explore Python you'll see their uses
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
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}
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]
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()
Introduction to Flask. Date TBA
Python Ireland
Fork the DUCSS site and hack away!
DUCSS in 4th Week