+List Comprehensions
+Garbage Collection
+Nested Scopes (2.2)
+Type Unification (2.2)
+Generators (2.2)
print => print()
"There should be one— and preferably only one —obvious way to do it"
Python => Javascript
Python => Javascript
Python => Javascript
Python <=> Lisp
High Performance Virtual Machine
Python <=> .NET
Python <=> Java
'flyweight', python-on-a-chip
RPython + JIT == Speed!
Python < 64Kb
The default
$ python hello.py
Hello World!
$ python
Python 2.6.6 (r266:84292, Nov 21 2013, 10:50:32)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print('Hello World!')
Hello World!
>>>
$ ipython
Python 3.4.3 (default, Feb 25 2015, 21:28:45)
Type "copyright", "credits" or "license" for more information.
IPython 3.0.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]:
$ ipython notebook
also runs Julia, and R...
$ ipython notebook
$ ipython notebook
$ ipython notebook
find.py
draw.py
*.py
Python VM
OS
hardware
Telling the "machine" how to do something, and as a result what you want to happen.
def printEvenNumbers (listOfNumbers):
for x in listOfNumbers:
if x % 2 == 0:
print x
else:
print False
printEvenNumbers(naturalNumbers)
naturalNumbers = [0,1,2,3,4,5,6,7,8,9]
Telling the "machine" what you want to happen.
def evenNumber (x):
return (x % 2) == 0
print(map(evenNumber, naturalNumbers))
naturalNumbers = [0,1,2,3,4,5,6,7,8,9]
# Python 2
print 'Hello World!'
# Python 3
print('Hello World!')
# Long types (t.ex 45L) are of unlimited size. Eg: 42, 0, -567, 77777777777
40 + 42.67
int(67.879)
float(12)
long(345353524253453453453)
result = 1 / 3.0
print '{0:3.2f}'.format(result) # Python 2
print('{0:3.2f}'.format(result)) # Python 3
complex(5)
complex(45, 78)
Integers are limited by sys.maxint in Python 2
Other modules for mathematical operations are random, math, etc.
name = 'python'
list(name) # ['p', 'y', 't', 'h', 'o', 'n']
name + name # 'pythonpython'
name * 3 # 'pythonpythonpython'
len(name) # 6
string[n] gives the character at the nth position.
Since strings are lists, you can iterate over them
# Get character at position n, 0-based
name[1]
# Iterate over a string
for character in name:
print(character)
'a' in name # returns True
'z' in name # returns False
'yth' in name # returns True
print('My name is %s and my weight is %f kg.' % (name, 78.8))
str = """ The big brown fox
quickly jump ed over the wall
and ran away.
"""
print(r"Use \n fox new line")
import re
m = re.search('(?<=-)\w+', 'spam-egg')
m.group(0) # 'egg'
filename = 'foo'
extension = 'log'
'.'.join([filename, extension]) # 'foo.log'
emptyList = []
languages = ['python', 'erlang', 'java', 'c++', 'c']
languages + ['jython'] # ['python', 'erlang', 'java', 'c++', 'c', 'jython']
['Hello'] * 4 # ['Hello', 'Hello', 'Hello', 'Hello']
languages.append(['brython', 'ironpython']) # adds a list to the list
languages.extend(['stackless', 'shedskin']) # extends the list with the contents of a list
'python' in languages # returns True
'javascript' in languages # returns False
languages = ['python', 'erlang', 'java', 'c++', 'c']
sorted(languages)
sorted(languages, reverse=True)
mixedList = [12, 'Stockholm', 67.65, complex(34, 56)]
languages = [('Stockholm', 5), ('Oslo', 4), ('Helsinki', 2), ('Copenhagen', 1), ('Zurich', 3)]
def get_key(city_pair):
return city_pair[1]
print(sorted(languages, key=get_key))
squares = []
for x in range(10):
squares.append(x**2)
squares = [x**2 for x in range(10)]
# returns square of 0-9 if number is even
squares = [x**2 for x in range(10) if x %2==0 ]
# combines the elements of two lists if they are not equal
notEqualCombinations = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
myList = ['a', 'b', 'mpilgrim', 'z', 'example']
myTuple = ('a', 'b', 'mpilgrim', 'z', 'example')
myList[3] = 'c' # ['a', 'b', 'mpilgrim', 'c', 'example']
myTuple[3] = 'c'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
europe = {'sweden':'stockholm', 'norway':'oslo', 'finland':'helsinki', 'denmark':'copenhagen'}
europe['france'] = 'paris'
europe.get('norway')
'sweden' in europe # returns True
'china' in europe # returns False
movies = {'The Game of Shadows': [129, 'Mystery', 'Guy Ritchie', 2011],
'The Dark Knight': [126, 'Action', 'Christofer Nollan', 2008],
'Sherlock Holmes': [128, 'Mystery', 'Guy Ritchie', 2009],
'Interstellar': [169, 'SciFi', 'Christofer Nolan', 2014]}
sorted(movies) # returns movies sorted by title
def get_sort_key(value):
return value[3]
sorted(movies.values(), key=get_sort_key) # returns movies sorted by year
movies = {'The Game of Shadows': [129, 'Mystery', 'Guy Ritchie', 2011],
'The Dark Knight': [126, 'Action', 'Christofer Nollan', 2008],
'Sherlock Holmes': [128, 'Mystery', 'Guy Ritchie', 2009],
'Interstellar': [169, 'SciFi', 'Christofer Nolan', 2014]}
newMovies = { key: value for key, value in movies.items() if value[3] > 2010 }
index = 0
while index < len(names):
print (names[index])
index+=1
for name in names:
print name
names = ['Larry', 'Moe', 'Curly']
count = 0
for name in names:
print(i, name)
count += 1
for i, name in enumerate(names):
print(i, name)
names = ['Larry', 'Moe', 'Curly']
for i, name in enumerate(names, start=1):
print(i, name)
my_long_text = "We are no longer the knights who say Ni! We are now the knights who say ekki-ekki-ekki-p'tang-zoom-boing-z'nourrwringmm!"
my_long_text = ("We are no longer the knights who say Ni! "
"We are now the knights who say ekki-ekki-"
"ekki-p'tang-zoom-boing-z'nourrwringmm!")
if 'x' in d and isinstance(d['x'], str) and d['x'].isdigit():
value = int(d['x'])
else:
value = None
try:
value = int(d['x'])
except (KeyError, TypeError, ValueError):
value = None
d = {'x': '5'}
if __name__ == '__main__':
def main():
print('Doing stuff in module', __name__)
if __name__ == '__main__':
print('Executed from the command line')
main()
# utility.py
pi = 3.14285
def get_circle_area(radius):
return pi * radius**2
# circle.py
import utility
print(utility.pi)
print(utility.get_circle_area(10))
# circle.py
from utility import get_circle_area
print(get_circle_area(10))
to use everything in utility.py:
to use only a specific method from utility.py:
int a = 1;
Not Python:
int a = 2;
Not Python:
int b = a;
Not Python:
a = 1
Python:
a = 2
Python:
b = a
Python:
def get_full_name(fname, lname='Andersson'):
return fname + ' ' + lname
get_full_name('Nisse')
get_full_name('Nisse', 'Pettersson')
def add(a, b, c, d):
return a + b + c + d
add(4, 7, 8, 2) # Values are assigned by positions
add(b=42, c=45, d=87, a=34) # Values are assigned by argument names or keyword names
add(32, 67, d=66, c=12) # Mix of the above
def foo(*args):
print(args) # args is a tuple that collects all the incoming arguments
foo(34, 56, 78)
def foo(**kwargs):
print(kwargs) # kwargs is a dictionary. This works only for keyword-value based calls
foo(fname='John', lname='Doe')
def foo(a, b, *args, **kwargs):
print(a)
print(b)
print(args)
print(kwargs)
def change_value(value):
value = 42
some_value = 50
print(some_value) # 50
change_value(some_value)
print(some_value) # 50
def change_list(some_list):
some_list.append(42)
another_value = [1, 2, 3, 4, 5]
print(another_value) # [1, 2, 3, 4, 5]
change_list(another_value)
print(another_value) # [1, 2, 3, 4, 5, 42]
def get_even(number):
while True:
if number % 2 == 0:
yield number
number += 1
>>> generator = get_even(33)
>>> generator.next()
34
>>> generator.next()
36
def heading(func):
def wrapper(name):
return "<h1>{0}</h1>".format(func(name))
return wrapper
@heading
def greet(name):
return "Hello {0}, i hope you are well!".format(name)
print greet("John Doe") # <h1>Hello John Doe, i hope you are well!</h1>
You can also execute the wrapped function, giving you the ability to do something before and after the function executes.
items = [1, 2, 3, 4, 5]
def sqr(x):
return x ** 2
list(map(sqr, items)) # [1, 4, 9, 16, 25]
Map takes a function and a collection of items. It makes a new, empty collection, runs the function on each item in the original collection and inserts each return value into the new collection. It returns the new collection.
items = [0, 1, 2, 3, 4]
def add(a,x):
return a + x
sum = reduce(add, items) # 10
Reduce takes a function and a collection of items. It returns a value that is created by combining the items.
items = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
def negative(x):
if x < 0:
return x
list(filter(negative, items)) # [-5, -4, -3, -2, -1]
Filter takes a function and a collection. It returns a collection of every item for which the function returned True.
def twice(function, x):
return function(function(x))
def f(x):
return x + 3
twice(f, 7) # 13
higher-order functions are functions that can accept other functions as arguments and return functions to the caller.
def square(x):
return x**2
square(8) # 64
(lambda x: x**2)(8) # 64
An anonymous function is a function definition that is not bound to an identifier.
def fizzbuzz(number):
if number % 3 == 0 and number % 5 == 0:
return 'FizzBuzz'
elif number % 3 == 0:
return 'Fizz'
elif number % 5 == 0:
return 'Buzz'
else:
return number
for number in range(1, 101):
print fizzbuzz(number)
import sys
class Value(object):
def __init__(self,value):
self.setValue(value)
def setValue(self,value):
self.value = value
def getValue(self):
return self.value
def toString(self):
return self.getValue().__str__()
class FizzBuzz(object):
def __init__(self, n):
if n % 15 == 0:
value = 'FizzBuzz';
elif n % 3 == 0:
value = 'Fizz';
elif n % 5 == 0:
value = 'Buzz';
else:
value = str(n);
self.setValue(value);
def setValue(self,value):
self.value = Value(value);
def getValue(self):
return self.value;
class FizzBuzzRunner(object):
def __init__(self, n):
self.setN(n)
def setN(self, n):
self.n = n
def run(self):
for i in range(1,self.n):
sys.stdout.write(FizzBuzz(i).getValue().toString()+'\n');
if __name__ == '__main__':
n = 101;
FizzBuzzRunner(n).run()
def main():
i = 0;
value = '';
while i < 100:
i += 1
if i % 15 == 0:
value = 'FizzBuzz';
elif i % 3 == 0:
value = 'Fizz';
elif i % 5 == 0:
value = 'Buzz';
else:
value = str(i);
print value;
return 0;
main();
def fizzbuzz(n):
return 'FizzBuzz' if n % 3 == 0 and n % 5 == 0 else None
def fizz(n):
return 'Fizz' if n % 3 == 0 else None
def buzz(n):
return 'Buzz' if n % 5 == 0 else None
def fizz_andor_maybenot_buzz(n):
print fizzbuzz(n) or fizz(n) or buzz(n) or str(n)
map(fizz_andor_maybenot_buzz, xrange(1, 101))
fizzbuzz = lambda n: 'FizzBuzz' if n % 3 == 0 and n % 5 == 0 else None
fizz = lambda n: 'Fizz' if n % 3 == 0 else None
buzz = lambda n: 'Buzz' if n % 5 == 0 else None
fizz_andor_maybenot_buzz = lambda n: fizzbuzz(n) or fizz(n) or buzz(n) or str(n)
print reduce(lambda m,n: m+'\n'+n, map(fizz_andor_maybenot_buzz, range(1, 101)))
# utility.py
class Utility:
def add(self, a, b):
return a+b
def sub(self, a, b):
return a-b
def multiply(self, a, b):
return a*b
# test_utility.py
import unittest
from utility import Utility
class TestUtility(unittest.TestCase):
util = None
def setUp(self):
self.util = Utility()
def tearDown(self):
self.util = None
def test_add_with_positive_values(self):
a = 10
b = 20
expected_value = 30
actual_value = self.util.add(a, b)
self.assertEquals(expected_value, actual_value)
def test_add_with_positive_and_negative_values(self):
a = -10
b = 20
expected_value = 10
actual_value = self.util.add(a, b)
self.assertEquals(expected_value, actual_value)
if __name__ == "__main__":
unittest.main()
Style Guide for Python Code
Docstring Conventions
Extended Iterable Unpacking
The global interpreter lock, or GIL, is a mutex that prevents multiple native threads from executing Python bytecodes at once
Python’s default arguments are evaluated once when the function is defined, not each time the function is called. This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
def create_multipliers():
return [lambda x : i * x for i in range(5)]
for multiplier in create_multipliers():
print(multiplier(2))
# expected
0
2
4
6
8
# actual
8
8
8
8
8
whenever any of the returned functions are called, the value of i is looked up in the surrounding scope at call time. By then, the loop has completed and i is left with its final value of 4.
# Correct
foo.close()
# Incorrect, but no error :(
foo.close
...
...
...
...
...
...
...
...
...
...
(PEP 20)
import this