César D. Velandia

Python


Quick start


#!/usr/bin/env python
print "Hello World"

Lists

a = [1,2,3,4,5,6]

a[0:1] # first element

a[2:4] # slice mid elements, second parameter is exclusive

a[2:] # all elements after third element

Is an element included in a list

Check if element is contained

fruits = ["apple", "pear" , "orange"]
"pear" in fruits
>> True

if "grape" in fruits:
	print "there is a grape"
>>> ...

Dictionaries

a = {"name": "Bob", "age": 20}
>> {'age': 20, 'name': 'Bob'}
a.keys()
>> ['age', 'name']

Check whether a KEY is contained and delete a key-value pair

if 'name' in a: 
	del(a['name']); 
	print a

>> {'age': 20}

Dictionaries and Lists combined

x = {"name": "John Doe", "interests": ["running", "reading", "swimming"]}
print x
>> {'interests': ['running', 'reading', 'swimming'], 'name': 'John Doe'}
print x['interests']	
>> ['running', 'reading', 'swimming']
x['interests'].append('jumping')
print  x
>> {'interests': ['running', 'reading', 'swimming', 'jumping'], 'name': 'John Doe'}

Loops

Lists

food = ['ice cream', 'hot dog', 'pancake']
for item in food:
        print item

# or

i = 0
while (i < len(food)):
	print food[i]
    i = i + 1

Dictionaries

food = {'dessert':  'ice cream', 'meal':  'hot dog', 'breakfast': 'pancake'}
for key in food:
	print "key is "+ key + " and value is "+ food[key]

List comprehensions

LCs aren't more efficient than loops, only shorter and more readable (in some cases)

with_loop = []

for i in range(100):
    if i % 2 == 0:
        with_loop.append(i*100.0)
    else:
        with_loop.append(-1)


with_comprehension = [i*100.0 if i % 2 == 0 else -1 for i in range(100)]

assert(with_loop == with_comprehension)

forinresult = operate iteratorlistfilterternary styleif ... else ...call external func or operatorsfn(), *, +, -, / ...nested ok! inner loop = right side[]

if filter block doesn't affect the output element, then filter block goes at the end, e.g.,

matches = [word for word in words if snippet in word.lower()]

more examples

# simple division
return [datum/divisor for datum in data_list for divisor in div_list]

# simple if else
def find_usable_data(data_list):
return [datum if datum > 90 and datum % 2 == 0 else -100 for datum in data_list ]

# calling a fn
return [cos_correction(datum, angle) for datum in data_list for angle in [0, 15, 60, 90]]

# nested loop (inner loop, right most)
return [i*j for i in range(100) for j in range(10)]

# dictionary comprehension
return {key:(value**3)/(2**value) for key, value in data_dict.items()}

Functions

def analyse(l):
	# do something
	return

# call function like
results = analyse([1,2,3,4])

Exceptions

import sys

try:
        print 5 / 0
except Exception as e:
        print "exception", type(e), e

print "no sweat"

Bottle framework

Handle urls with a decorator

import bottle

@bottle.route('/')
def main():
    return '<b> Hello %s </b>' % item['name']

Separating the view

# In hello_world.py
import bottle

@bottle.route('/')
def home():
        mythings = ['apple', 'banana', 'peach']
        return bottle.template('hello_world', username= 'Larry', things=mythings)

bottle.debug(True)
bottle.run(hosts='localhost', port=8080)

template file hello_world.tpl

<!DOCTYPE html>
        <head>
                <title>Hello there </title>

        </head>
        <body>
                <p> Welcome {{username}} </p>
                <ul>
                %for thing in things:
                        <li>{{thing}} </li>
                %end
                </ul>
        </body>
</html>

managing a post

import bottle

@bottle.route('/')
def home():
        mythings = ['apple', 'banana', 'peach']
        return bottle.template('fruit_form', {'username': 'Larry', 'things' : mythings})


@bottle.post('/favorite_fruit')
def favorite_fruit():
        fruit = bottle.request.forms.get("fruit")
        if (fruit == None or fruit == ""):
                fruit = "No selection"
        return bottle.template('fruit_selection.tpl', {'fruit': fruit})

bottle.debug(True)
bottle.run(hosts='localhost', port=8080)

fruit_form.tpl

<!DOCTYPE html>
        <head>
                <title>Hello there </title>
        </head>
        <body>
                <p> Welcome {{username}} </p>
                <ul>
                %for thing in things:
                        <li>{{thing}} </li>
                %end
                </ul>
                <form action="/favorite_fruit" method="POST">
                        What is your fav fruit?
                        <input type="text" name= "fruit" size=40 value=""><br/>
                        <input type="submit" value="Send">
                </form>
        </body>
</html>

fruit_selection.tpl

<!DOCTYPE html>
        <head>
                <title>Hello there </title>
        </head>
        <body>
                <h1>
                  Thank you! You've selected {{fruit}}
                </h1>
        </body>
</html>

Managing cookies

import bottle

@bottle.route('/')
def home():
        mythings = ['apple', 'banana', 'peach']
        return bottle.template('fruit_form', {'username': 'Larry', 'things' : mythings})


@bottle.post('/favorite_fruit')
def favorite_fruit():
        fruit = bottle.request.forms.get("fruit")
        if (fruit == None or fruit == ""):
                fruit = "No selection"

        bottle.response.set_cookie("fruit", fruit)
        bottle.redirect("/show_fruit")

@bottle.route('/show_fruit')
def show_fruit():
        fruit = bottle.request.get_cookie("fruit");
        return bottle.template('fruit_selection.tpl', {'fruit': fruit})



bottle.debug(True)
bottle.run(hosts='localhost', port=8080)

Conda

is an open source package management system and environment management system for installing multiple versions of software packages and their dependencies and switching easily between them.

Environments

Check installation details

conda info

List existing conda environments

conda info --envs
conda info -e

Create environment and install dependencies

conda create --name snowflakes biopython
conda create --n snowflakes biopython

> Fetching package metadata: ....
> Solving package specifications: .
> Package plan for installation 
> in environment C:\Users\USER\Anaconda\envs\snowflakes:>	
> 
> The following packages will be downloaded:
> 
>     package          |            build
>     -----------------|-----------------
>     biopython-1.65   |       np19py27_0    2.0 MB
> 
> The following NEW packages will be INSTALLED:
> 
>     biopython:  1.65-np19py27_0
>     numpy:      1.9.2-py27_0
>     pip:        7.1.0-py27_0
>     python:     2.7.10-0
>     setuptools: 18.0.1-py27_0

Dependency conflicts (between packages) are avoided by  installing in the env at the same time

Environment default location  C:\Users\USER\Anaconda\envs
override with --path c:\env

Start using environment (UNIX systems require source)

(source) activate snowflakes

Exit with...

deactivate

Creating a new env with Python 3.4

conda create -n bunnies python=3.4 astroid

Clone an existing environment

conda create -n kittens --clone bunnies

Python

Check available python versions

conda search --full-name python
conda search -f python

Install Python3.4 in new env and activate

conda create -n snakes python=3.4
activate snakes

.condarc configuration

Get all keys from config file

conda config --get

Get channel keys from config file

conda config --get channels

Add new channel pandas. Looks for packages there

conda config --add channels pandas

Packages

See all packages in environment

conda list

Look for a package (if available)

conda search beautiful-soup	

Install package to environment (or current active). All packages available via conda install

conda install -n bunnies beatiful-soup

Update package in current environment

conda update beautiful-soup

Search in a specific location, e.g., pandas channel

conda search --override-channels -c pandas bottleneck

Install package from a given channel

conda install -c pandas bottleneck

Look for a package in Anaconda's repo

conda search --override-channels -c defaults beautiful-soup

Activate and pip-install a package

activate bunnies
pip install see

Install commercial packages

conda install iopro accelerate

Removing packages and environments

Remove 1 package from a named env, active environment

conda remove --name bunnies beautiful-soup
conda remove beautiful-soup

Remove multiple

conda remove --name bunnies beautiful-soup astroid

Remove environment

conda remove --name snakes --all

Sources

  1. http://conda.pydata.org/docs
  2. Conda cheat sheet