Wednesday, September 7, 2011

quick & dirty basic python reference - v1

this is definitely not a tutorial. just quick notes I took while reading two python books and playing with this nice&flexible language.


Getting around:

Get help:
>>> num = 10
>>> help(10)
Help on int object:

class int(object)
| int(x[, base]) -> integer
|
| Convert a string or number to an integer, if possible. A floating
| point argument will be truncated towards zero (this does not include a
| string representation of a floating point number!) When converting a
| string, use the optional base. It is an error to supply a base when
| converting a non-string.
|
| Methods defined here:
|
| __abs__(...)
| x.__abs__() <==> abs(x)
|
| __add__(...)
| x.__add__(y) <==> x+y
.
.
.

Basic commands and concepts:

>>>print 2*3
6

>>> x = 2
>>> x += 1
>>> x
3

>>> 2 ** 3 #power
8

>>>TextFromUser = raw_input( )


import sys - imports system library

sys.path.append - appends a floder to python path

if "somevalue" in sys.argv: - nice way to write an if statement when asking about a list item


reload(someScript) - reloads a script\library

from datetime import datetime.current - imports a specific function/member

from SomeScript import var1 , var2 , var3 , var4 - imports a specific function/member

>>> import random
>>> random.random( )
0.232425325
>>> random.choice([1,2,3,5,8,13,21,34,55])
13

>>> userdata = int(input("how old are you")) #get input from user
how old are you54
>>> userdata
54

Get a list of type's\object's function:

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> lst = [1,2,3,4,5]
>>> dir(lst)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Data types:

string:

>>> S = 'stringy'
>>> S[1]
't'
>>> S[-2]
'g'
>>> S[1:4]
'trin'
>>> S[1:]
'tringy'
>>> S[:2]
'st'
>>> len(S)
7
>>> S*3
'stringystringystringy'

#this is how we create multi-line string
os.environ["CFLAGS"] = "-W -Wimplicit-int " + \
"-Wimplicit-function-declaration " + \
"-Wimplicit -Wmain -Wreturn-type -Wunused -Wswitch "

Dictionary:

>>> dict = {'felix':'cat','rex':'dog','num':2}
>>> dict['num'] -= 2
>>> dict['num']
0

list:

>>> lst1 = [1,2,3,4,5]
>>> lst1
[1, 2, 3, 4, 5]
>>> lst1[1:]
[2, 3, 4, 5]
>>> lst1[:-1]
[1, 2, 3, 4]
>>> lst1[-3:]
[3, 4, 5]
>>> lst2 = [1,2,[1,2,3,4],1,1,2,2]
>>> lst2[2]
[1, 2, 3, 4]
>>> lst2.append(1)
>>> lst2
[1, 2, [1, 2, 3, 4], 1, 1, 2, 2, 1]
>>> lst3 = lst2 * 2
>>> lst3
[1, 2, [1, 2, 3, 4], 1, 1, 2, 2, 1, 1, 2, [1, 2, 3, 4], 1, 1, 2, 2, 1]
>>> lst4 = [11,22,33,44,55]
>>> lst4.pop(1)
>>> lst4
[11,33,44,55]

>>> multidimlist = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
>>> multidimlist[1][1]
5

>>> multidimlist = [[1,2,3],[4,5,6],[7,8,9]]
>>> [row[0] for row in multidimlist]
[1, 4, 7]

>>> [{row[0],row[1]} for row in multidimlist if row[0] > 3 and row[1] < 9]
[set([4, 5]), set([8, 7])]

tuple: (same as list just immutable):

>>> tup = (1,1,1,1,1,1,2,2,2,3,4,5,6)
>>> tup.count(2)
3

Set:

>>> s1 = set([1,2,3,4,5])
>>> s2 = set([3,4,5,6,7,8])
>>> s1 & s2
set([3, 4, 5])
>>> s1 - s2
set([1, 2])
>>> s2 - s1
set([8, 6, 7])
>>> s1 | s2
set([1, 2, 3, 4, 5, 6, 7, 8])

type: (for 'reflection\introspection' operations)

>>> sample_set = set([1,2,3])
>>> type(sample_set)


class:

class hunter:
def __init__(self,name,age): #init when created
self.name = name
self.age = age
def hunt(self,animal):
return str(animal) + " hunted"

>>> jack = hunter.hunter('jack',22)
>>> jack.hunt('joe')
'joe hunted'


Functions:

Define a function:

>>> def fact(n):
""" calculates the factorial """
r = 1
while n >0:
r = r*n
n = n - 1
return r


Run the function:
>>> fact(4)
24

Define a function with named parameters and with default values:
>>> def myPower(arg1 , arg2=2):
x = 1
counter = arg2
while counter > 0:
x = arg1 * x
counter = counter - 1
return x

Run the function:
>>> myPower(3)
9
>>> myPower(2,8)
256
>>> myPower(arg2 = 8 , arg1=2)
256

Define a function undefined number of args:
>>> def Contains10(*nums):
current = 0
for num in nums:
if num == 10:
return 'true'
return 'false'

Run the function:

>>> Contains10(10,22)
'true'
>>> Contains10(1,2,3)
'false'

Function is a first class citizen - can be passed as a parameter or set to a variable:

>>> ct = Contains10
>>> ct(10,2,3)
'true'

Function that gets another function as argument and returns a new funcion - decorator pattern:

>>> def logTime(func):
from datetime import datetime
print("setting time logging decoration to ", func.__name__)
def wrapperFunc(*args):
print("start " , func.__name__, " - " , datetime.now())
func(*args)
print("finish " , func.__name__, " - " , datetime.now())
return wrapperFunc

Apply decorator to a function:

>>> @logTime
def takesLongTime():
i = 0
while i < 1000000000:
i += i + 2
return i

setting time logging decoration to takesLongTime


Run the function:
>>> takesLongTime()
start takesLongTime - 2011-09-08 00:42:33.682000
finish takesLongTime - 2011-09-08 00:42:33.710000

Working with files\web\database:

working with files:
>>> f = open('c:\example.txt', 'w')
>>> f.writelines('I am the first line')
>>> f.write('I am some more text')
>>> f.close()

the file now contains -> "I am the first lineI am some more text"

>>> f = open('c:\example.txt')
>>> f.read()
'I am the first lineI am some more text'

>>> import os
>>> for root, dirs, files in os.walk('c:\\playpython'):
print("{0} has {1} files".format(root , len(files)))

c:\playpython has 6 files
c:\playpython\1dir has 1 files
c:\playpython\2dir has 6 files



Working with web client: (urllib2)

>>> import urllib2 as u
>>> webpage = u.urlopen('http://www.cnn.com')
>>> webpage.read(400)
'CNN.com International - Breaking, World, Business, Sports, Entertainment and Video News \nWorking with mongodb:

>>> import pymongo
>>> from pymongo import Connection
>>> conn = Connection('localhost', 666) #connect to mongodb on local machine over port 666
>>> db = conn('myDB) #open specific db inside mongodb server
>>> collection = db.customers #get a specific collection



No comments: