Skip to content

Instantly share code, notes, and snippets.

@brev
Last active July 26, 2017 16:21
Show Gist options
  • Save brev/9111002a15672844a50b to your computer and use it in GitHub Desktop.
Save brev/9111002a15672844a50b to your computer and use it in GitHub Desktop.
Python Cookbook

Python Cookbook

  • Programs are composed of modules,
  • Modules contain statements,
  • Statements contain expressions,
  • Expressions create and process objects.

Functions

def add(a, b):
  return a + b
  
print add(3, 5)  # 8

Lambdas

Lambdas are anonymous functions. Helpful for functional programming like map, reduce, etc.

def timesThree(a):
  return a * 3

ints = [1, 2, 3, 4, 5]
mults = map(timesThree, ints)  # [3, 6, 9, 12, 15] 

mults = map(lambda a: 3 * a, ints)  # [3, 6, 9, 12, 15]

Code Re-use

Module Attributes

# MyFile.py
title = "Meaning of Life"
% python
>>> import MyFile
>>> print MyFile.title  # "Meaning of Life"

Modules

A module groups a set of functions and classes. Any Python source file is a module when loaded with import.

# Above `Account` class has been put into `account.py`

import account
checking = account.Account("Bob, 1234.56)

# another way
from account import Account
checking = Account("Bill", 4321.32)

Packages

A package is a collection of modules and subpackages. Any directory with Python source files, and an __init__.py file, is a package.

Sub-packages are just sub-directories with their own __init__.py files.

# Above `Account` class has been put into `./bspell/` directory, and file `__init__.py` has been created

from bspell import account
checking = account.Account("Bob, 1234.56)

# another way
from bspell.account import Account
checking = Account("Bill", 4321.32)

Objects

Everything in Python is an object (class instance), and has:

  • identity
  • type
  • value

New types of objects can be created with class. Classes have:

  • variables
  • methods

Classes

Constructor methods are named __init__.

class Account:
  "A simple class"
  kind = "Checking"
  def __init__(self, name, balance):
    self.name = name
    self.balance = balance

account = Account("Bob", 1234.56)

Object Data Types

Object Type Example creation and/or literals
Numbers 1234, 3.1415
Strings 'hello', "Hey"
Lists [1, 2, 3]
Dictionaries {'name': 'Brev'}
Tuples (1,'spam', 4,'you')
Files myfile = open('filename.txt', 'r')
Other Sets, types, None, Booleans

Numbers

Strings

  • Python strings are immutable and cannot be changed.
  • Single and Double quotes are the same.
  • Raw string format: r'backslash-no-work'
  • Unicode string format: u'Иyet my friend'
  • String objects do not contain pattern matching functionality!
phrase = 'Hello'
print len(phrase)  # 5 
print phrase[0]  # first item 'H'
print phrase[-1]  # last item 'o'
print phrase[-2]  # second to last item 'l'
print phrase[1:3]  # slice 'ell'
print 'Hell' + 'o!'  # concatenate 'Hello!'
print 'Hey' * 3  # repeat 3 times 'HeyHeyHey'
print "Balance is $%.2f" % account.getBalance()  # sprintf style
print dir(phrase)  # List all string object methods available

String encoding methods:

S = 'X\nY\tZ'
len(S)  # 5
ord('\n')  # ASCII value 10

Multiple string literal via triple quote (aka HEREDOC):

msg = """
xxxxx
yyy'yy""y
zzz"""

Lists

  • Lists are mutable and can be modified in-place

Dictionaries

Tuples

Files

Sets

Types

None

Boolean

??? Pattern Matching

import re
match = re.match('Hello(.*)World(.*)', 'Hello Wide World Web')
match.group(1)  # ' Wide '
match.groups()  # (' Wide ', ' Web ')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment