Python Reminders

if/else Control Flow

if cond:  
    action
elif cond:  
    action
...
else:  

Try/Except

Capture situation where program may fail and offer alternative instruction

try:  
    action # try this
except:  
    action # if try fails, do this

Functions

def function_name(*kwargs):  
    action
    return

Loops

while cond:  
    action
    if cond:
        break # drop out of loop
    if cond: 
        continue # restart at while


for i in [1,2,3,4,5]:  
    action
    # break/continue function in same manner

Loop Idioms

nums = list()  
for i in range(1,5):  
    nums.append(i+i)

Conditionals

x = None # specialty type  
if x is None  
if x is not None  
if x is FALSE  

Python Regex

import re  
  • ^ Matches the beginning of a line
  • $ Matches the end of the line
  • . Matches any character
  • \s Matches whitespace
  • \S Matches any non-whitespace character
  • * Repeats a character zero or more times
  • ? Repeats a character zero or more times (non-greedy)
  • + Repeats a character one or more times
  • +? Repeats a character one or more times (non-greedy)
  • [aeiou] Matches a single character in the listed set
  • [^XYZ] Matches a single character not in the listed set
  • [a-z0-9] The set of characters can include a range
  • ( Indicates where string extraction is to start
  • ) Indicates where string extraction is to end

Sockets

import socket  
mysock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)  
mysock.connect(('www.google.ca',80))

urllib

import urllib  
  • urllib.urlopen(url)