« Back to home

Notes on Python

Basic operations

List slicing

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]

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)

Comments

comments powered by Disqus