Introductions
Objectives
Documentation
Environment
interpreted
object oriented
dynamic
strongly typed
... used (almost) everywhere
Python 2 vs Python 3
Wes McKinney, Python for Data analysis, O'Reilly, 2013, p.11
... on Integrated Development Environments (IDEs)
http://www.python.org/dev/peps/pep-0008/
a = 12
b = a
id(a)
142708844
id(b)
142708844
n = None # NoneType: special value meaning... nothing
b = True # bool: boolean... True or False (case sensitive)
i = 15 # int: integer
f = 15.5 # float: non-integer values
s = "string" # str: strings, written with "" or ''
u = u"string" # unicode: unicode string, writh with u"" or u''
l = [] # list: list of objects (ordered)
t = () # tuple: immutable list of objects (can't append to it)
d = {} # dict: dictionary of data (unique, unordered)
st = {} # set: a collection of objects (unique, unordered), set([])
coord = (45.30, 73.34)
lat, lon = coord
str(), int(), float(), bool(), list(), tuple(), dict(), set()
float(a)
12.0
l = [[1,2,3],[4,'ohai',6],[7,8,9]]
d = {1611: {'lastname':u'Gutiérrez Hermoso', 'firstname':u'Jordi'},
123: {'lastname':u'Leduc-Hamel', 'firstname':u'Mathieu'}}
l[2]
d[1611]
l[1][1]
'ohai'
l[1:3]
[[4, 'ohai', 6], [7, 8, 9]]
type() # returns object's type
dir() # returns the object's attributes
help() # gives an object's documentation
callable() # whether an object is function-like...
def my_function(param1, param2, param3=None, param4=0, *args, **kwards):
"""This is my function."""
output = True
return output
variable. [+ tab]
variable?
type()
dir()
help()
exploring the types
name = u"Jordi Gutiérrez Hermoso"
firstname, paternalname, maternalname = name.split()
paternalname.upper()
paternalname.lower()
paternalname.ljust(30)
name = [firstname.lower(), paternalname.lower(), maternalname.lower()]
username = ".".join(name)
name = u"Jordi Gutiérrez Hermoso"
username = ".".join(name.split()).lower()
users = []
users.append(username)
jordigh = {'firstname':u'Jordi', 'lastname':u'Gutiérrez Hermoso'}
mathieu = {'firstname':u'Mathieu', 'lastname':u'Leduc-Hamel'}
jp = {'firstname':u'Jean-Philippe', 'lastname':u'Caissy'}
people = []
people.append(jordigh)
people.append(mathieu)
people.append(jp)
status = [
(1, u'New'),
(2, u'In progress'),
(3, u'Rejected'),
(4, u'Accepted'),
]
numlist = range(6)
if 5 in numlist:
print 'hooray 5'
elif 4 in numlist:
print 'hooray 4'
else:
print 'not hooray :-('
hooray 5
'hooray 5' if 5 in numlist else 'not hooray :-('
'hooray 5'
year = 2012
while year <= 2015:
print year
year = year + 1 # year += 1
2012 2013 2014 2015
for i in range(2012, 2016):
print i
2012 2013 2014 2015
#! /usr/bin/env python
# -*- encoding: utf-8 -*-
def sup(name):
return u"Sup %s!" % (name)
if __name__ == '__main__':
print u"--------------------------------------------------"
print u"START the script"
print u"--------------------------------------------------"
name = raw_input("What is your name? ")
print sup(name)
print u"-----------------------------------------------"
print u"END the script"
print u"-------------------------------------------------"
-------------------------------------------------- START the script -------------------------------------------------- ----------------------------------------------- END the script -------------------------------------------------
shebang: #!/usr/bin/env python
encoding: # -*- encoding: utf-8 -*-
if __name__ == '__main__':
raw_input()
create a repository project/contacts
create in this repo a Python script called form.py which:
Execution in ipython:
lab.py
class Person(object):
def __init__(self, name, firstname, dob=None):
self.name = name
self.firstname = firstname
self.dob = dob
def age(self):
# TODO : compute in function of dob and now
return self.dob
mathieu = Person("Leduc-Hamel", "Mathieu")
davin = Person(firstname="Davin", name="Baragiotta")
import module
from module import name
from module import name as my_name
built-in: no need to import
standard library (shipped with python): import without installation
pypi : lots of modules to install that are just begging to be imported
importable if installed "in the path"
from datetime import date
today = date.today()
print today
#year = ??
2014-03-18
import sys
sys.path
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/jordi/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/IPython/extensions']
inpsych
__init__.py
file in itlab.py
file in the inpsych
directoryage
function living in the lab.py
file in order to test itinpsych
directory is "in the path" for your interpretornltk
pattern
install with pip
pip = pip installs python
f = open('python.txt')
for line in f.readlines():
print line,
f.close()
Python is a language that I love and, it seems, its name comes from the Monty Python troupe of British comedians and not from the kind of snake called "python"
f = open("python.txt")
lines = f.readlines()
f.close()
target = 'python'
context = [line for line in lines if target in line]
comments = [line for line in lines if line.startswith('#')]
test.txt
for n in range(10):
print "%d to the 3rd power is: %d" % (n, n**3)
for p in people:
print "Bonjour/Hello %s %s" % (p['firstname'], p['lastname'].upper())
0 to the 3rd power is: 0 1 to the 3rd power is: 1 2 to the 3rd power is: 8 3 to the 3rd power is: 27 4 to the 3rd power is: 64 5 to the 3rd power is: 125 6 to the 3rd power is: 216 7 to the 3rd power is: 343 8 to the 3rd power is: 512 9 to the 3rd power is: 729 Bonjour/Hello Jordi GUTIÉRREZ HERMOSO Bonjour/Hello Mathieu LEDUC-HAMEL Bonjour/Hello Jean-Philippe CAISSY
try:
15/0
except (ZeroDivisionError,), e:
print "Dividing by zero is bad, m'kay?"
print e
import pickle
f = open('pickles', 'w')
pickle.dump(status, f)
pickle.dump(people, f)
f.close()
exit()
import pickle
f = open('pickles')
pickle.load(f)
#objects = []
#for obj in pickle.load(f):
# objects.append(obj)
f.close()
lab.py
program, store all the responses obtained from the users in a .csv filehelpful community
Montréal-Python:
enjoy!
Create a script flux.py that returns the 5 latest stories posted on the Montreal-Python-site: http://montrealpython.org/fr/feed/
Take the time to code up the solution yourself... ... then you can compare with our solution
As a hint, our solution only has 8 lines of Python.