Beruflich Dokumente
Kultur Dokumente
Contents
Python operators.......................................................................................................................................................... 1
Sequence types:........................................................................................................................................................... 2
Unicode........................................................................................................................................................................ 2
String........................................................................................................................................................................... 2
Comment:.................................................................................................................................................................... 2
Multiple statement in one line...................................................................................................................................... 2
LIST.............................................................................................................................................................................. 2
Xrange not in python 3.0........................................................................................................................................... 2
Array - Store value of same type.................................................................................................................................. 3
Set (mutable but has class as immutable (frozen set)) :............................................................................................... 3
Tuple............................................................................................................................................................................ 3
Dict.............................................................................................................................................................................. 3
Time, date, calendar.................................................................................................................................................... 3
Format.......................................................................................................................................................................... 3
Random........................................................................................................................................................................ 3
Function:...................................................................................................................................................................... 4
Iteration....................................................................................................................................................................... 4
Exception..................................................................................................................................................................... 4
Assert........................................................................................................................................................................... 4
Class and Inheritance................................................................................................................................................... 4
Import.......................................................................................................................................................................... 5
Methods....................................................................................................................................................................... 5
Network programming................................................................................................................................................. 5
Socket.............................................................................................................................................................. 5
Import smtplib.................................................................................................................................................. 5
Xml parse........................................................................................................................................................ 5
Json.................................................................................................................................................................. 5
Database.......................................................................................................................................................... 6
Regular expression....................................................................................................................................................... 6
Popular functions.......................................................................................................................................................... 6
Python operators
Arithmetic Operators
o + Addition Adds values
a+b = ab
10+20 =30
o Subtraction
For A = 20 and B = 10; A-B = 10
o * Multiplication
o / Division
A/B =2
o % Modulus
A/B =0
o ** Exponent
A**2 = 400
o //
Floor Division
Result is the quotient of division. 11//2 = 5
With negative numbers the result is round away from zero. -11//3 = -3
Comparison (Relational) Operators and the result is true or false
o ==
o != and <> is true when condition fails. a<>b
o < , >, <=, >=
Assignment Operators
o = assign the value c = a+b
o +=, c+= a is same as c= c+a
o -=, *=, ++, /=, %=, **=, //=
Logical Operators
o or, not, and
Bitwise Operators
o Works on bit level, suppose b = 11110000 and c= 00001111
o And &, or |, XOR, ~complement, binary left shift << , binary right shift >>
o b&c = 0000 0000
o >>> x = 100 ,>>> x<<1 Prints 200
Membership Operators
o in
o not in
Identity Operators
o is
o is not
Sequence types:
o
o
Unicode
Unicode is str for python 3
Handle text, where text means it can be bigger than one byte
Text can be represented in special encoding text a raw byte -utf8 /latin-1
unicode('abcdef')
u'abcdef'
>>> s = unicode('abcdef')
>>> type(s)
<type 'unicode'>
Bytearray
Mutable
Gives the integer value of the character
S = bytearray(bhelloword)
Print S[1] will be 101
String
1. String operations.
a. String convert to int, float, double s1 =10, int(s1) , float(s1), double(s1),
b. Get the ASCII value :ord(a) = 97
c. Print(isfloat(12.34)) =>boolian value
d. Unichat(97) = ua and hex values 123c.decode(hex)
2. Substring
a. s1[6:10], S1[6:20:2]
b. Patition>>> s1.partition('the') =(' I am a string ', 'the', ' second part')
c. Split,s1.split() all element,
d. S1.split(None, 3) => total 4, first 4 and then rest,
e. s1.split('the', 3) => the is removed and only two parts,
f. S1.splitlines()list with lines ( in place of words)
3. String reverse : reverse letter by letter
a. Str.reverse()
4. Other methods: Max, min, len, count, startwith, swapcase, S1.traslate(None ,aeiou )
5. Python string, difference-between-find-and-index
a. Find will give -1
b. Index will give raises valueErroe
Comment:
LIST
Create an immutable sequential list. If using the large numbers, it is better to create the xrange.
Take same amount of memory for each creation
For num in xrange( -100,-120,-5):
Difference between range and xrange
Range is list, created the number of element when you define
My_array = array(I,[1,2,3,4])
Append, * ,insert,pop
Set (mutable):
Tuple
Loop in dict
o For K in d1: print d1[k]
o For k,v in d1.items(): print k,v
o For k,v in d1.iteritem(): print k,v
Format.
Random
Import random
o random.randint(start, stop),
o random.random()->0.678798
o randrange(start,stop,step)
o random.choice(string )
list = [random.choice(string.digits) for i in range (4)]
the above will generate the 4 random digits
o random.shuffle(l1) will shuffle the item in list
o l2 = random.sample(somelist,4)
Make list l2 from 4 random element of l1
Somelist = random.sample( ran
Random UUID
o functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as
specified in RFC 4122
o For unique ID call
Function:
import math
o math.sqrt(2)
def f1(a,m,n):
print I got 3 argument
sum = a+b+c
return sum
input() ->vaild python such as raw while raw_input() take anything and convert it in string
Iteration
For I in str
o Nice example for list iteration to get prime number
L2 = [n for n in another_list if n%2 ==0]
For I in [1,2,3,4}
While (condition): To break a loop , continue , break
Conditions
File operations
Open mode:
o
r, w, w+( for read/write , overwrite the file, create a file if no exits )
o
rb(binary read), r+ ( read, write, pointer at the begging)
o
a (append), a+
fh = open( filename, mode, buffer -> line buffering for1 , nobuffer =0)
fh = open(filename), open(filename, w) etc
File_read = Fh.read() = read in a string
fh.write(.) => write in a string
fh.Tell - > current curser position
fh.seek(0,0)
fh.close(), fh.name(), fh.mode()
Import os
os.rename(f1,f2)
os.remove(f1)
os.mkdir(), os.chdir(), os.getcwd()
Exception
Try/expectIOError/Expect
Try:
Code to read a file
ExceptIOError:
Print no such file
Except someother error:
Print
Assert
Can do on and off in the program
Raise when value is not correct.
assert(Temperature>=0),"Colder than absolute zero!" IF value is less than zero, it will raise an
error.
Class and Inheritance
Class : template
Attribute : field, variable
Method: code
Object :Instance of class: all of above (temp1)
Every method has self attribute
Attribute hide : by double __
class Employee: #Common base class for all employees
empCount = 0
def __init__(self, name, salary):
self.name = name
#Put self before the name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary,
emp = Employee( 'hs',100) # An object is created for class Employee with initial values hs and
100
emp.displayEmployee()
# Calling the method of class
emp.displayCount()
temp1 = Contractor("tmp2",200)
emp2 = Employee('e2',100)
# This Object may have the same values
Import
Methods
_abc ==This method is not imported when lib is imported
From M import * ( will not import _abc)
__init__ invoke 1st time
Network programming
For Mail
Import smtplib
Smltobj = smtplib.SMTP(mail.googl.com,25)
Smtlobj.sendmail(sender,reciver,mes)
Xml parse
It takes an xml file and purse it to find element ( like name) and attribute (like user1)
Import xlm.etree.ElementTree as ET
Tree = ET.parse(data.xml) == Data from disk
Root = tree.getroot()
For child in root: print child.tag, child.attribute
Or
Tree = ET.fromstring(data as string)
Tree.find(name).text
Json
Import json
Info = json.loads(in-data) = list/dict
For I in info: print name, I[name]
Jdump = json.dumps(in-data) ==== string
Len(info) - gives record count
Database
Import sqllite3
Conn = sqlllite3.connect(database name)
Cur = conn.curser()= like handle
Cur.excute
Conn.close()
Regular expression
Import re
o Fh = open(file), data = fh.read(), for line in data--- do the serach
o Re.search(From.+@ , line) , ^ From,
o Re.findall([a-zA-Z0-9]\S+@\S+[a-zA-Z0-9, line) full word that has @ in between
o ^X\S*: [0-9.}+ Start with X , any data till :, then space the digit and . Then more data :: XDSPAM-Confidence: 0.8475
o re.findall('^X\S*: ([0-9.]+)', line) 0.8475 look at palaneses
o ^ start with, \S any data not white space, \s white space , d digit, * zero or more , *? Non
greedy, + one or more, \A begin, \Z end,
o Match group
o Re.match gives you group
o Regex = r([a-zA-Z]+) (\d+)
o Match = re.match(regex, line)
o Match.group(), match.group(0), match.group(1), match.end()
Popular functions
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o
o