Python - newgeekorder/TechWiki GitHub Wiki

Back Home

See also:

Installation

Virtualenv is a tool that creates isolated Python development environments where you can do all your development work. To create a folder that works with different versions of python and pip installs

virtualenv virt

where virt is any folder. Virtualenv will create a folder structure with

.\bin
.\include
.\lib
.\local

Switching environment versions e.g. to pypy

> virtualenv -p /usr/bin/pypy pypy
Running virtualenv with interpreter /usr/bin/pypy
New pypy executable in pypy/bin/pypy
Installing setuptools, pip...done.

Language

Strings

# This prints out "John is 23 years old."
name = "John"
age = 23
print "%s is %d years old." % (name, age)

Any object which is not a string can be formatted using the %s operator as well.

# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print "A list: %s" % mylist

some more formatting options

%s - String (or any object with a string representation, like numbers)
%d - Integers
%f - Floating point numbers
%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X - Integers in hex representation (lowercase/uppercase)

String default functions

python has a number of default string functions

name = "richard" # type: string
print "my name is %s" %(name)
print name.upper()
print "location of %d " % name.index("i")
print "sub string 3 to 5, %s" % name[3:5]

Multi line strings

string = """line one
line two
line three"""
print string

will print out the strings as found including any indentations as found but

string2 = ("this is an "
          "implicitly joined "
          "string")
print string2

will print

this is an implicitly joined string

Conditions

name = "richard" 

if name == "richard" or name == "donovan":
    print "the name matched"
else:
    print "the name did not match"

if name in ["richard", "max"]:
    print "name matched again"

Loops

similarly ranges can be used for number looping

name = "richard" # type: string

for char in name:
    print char

print "##################\n"

for x in range(0, 3):
    print name[x]

prints

r
i
c
h
a
r
d
##################

r
i
c

While

while count < 5:
    print count
    count += 1  

Functions

def printName( name ):
    print "got name %s " % name
    return True

result = printName(name)
print "got result %s" % result

**Note: ** the function must be defined in the script before it can be called

Classes

class MyClass:
    variable = "blah"

    def function(self):
        print "This is a message inside the class."


mc = MyClass()
print mc.variable
mc.function()

Dictionaries (Python for Maps)

A dictionary is an array with key values

phonebook = {}
phonebook["John"] = 938477566
print phonebook["John"]
del phonebook["John"]

an alternative initialization phonebook = { "John":938477566 }

Json

The json library can parse JSON from strings or files. The library parses JSON into a Python dictionary or list. It can also convert Python dictionaries or lists into JSON strings.

Parsing JSON Take the following string containing JSON data:

json_string = '{"first_name": "Guido", "last_name":"Rossum"}'

It can be parsed like this:

import json
parsed_json = json.loads(json_string)

and can now be used as a normal dictionary:

print(parsed_json['first_name'])
"Guido"

You can also convert the following to JSON:

d = {
    'first_name': 'Guido',
    'second_name': 'Rossum',
    'titles': ['BDFL', 'Developer'],
}

print(json.dumps(d))
'{"first_name": "Guido", "last_name": "Rossum", "titles": ["BDFL", "Developer"]}'

simplejson The JSON library was added to Python in version 2.6. If you’re using an earlier version of Python, the simplejson library is available via PyPI.

simplejson mimics the json standard library. It is available so that developers that use older versions of Python can use the latest features available in the json lib.

You can start using simplejson when the json library is not available by importing simplejson under a different name:

import simplejson as json

After importing simplejson as json, the above examples will all work as if you were using the standard json library.

uJson

UltraJSON is an ultra fast JSON encoder and decoder written in pure C with bindings for Python 2.5+ and 3. https://pypi.python.org/pypi/ujson

import ujson
ujson.dumps([{"key": "value"}, 81, True])
'[{"key":"value"},81,true]'

ujson.loads("""[{"key": "value"}, 81, true]""")
[{u'key': u'value'}, 81, True]

Web Frameworks

Touch UI

Links and Reference