Sie sind auf Seite 1von 7

Python quick review

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

URLlib , READ page like a FILE.......................................................................................................................... 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

Mutable: list,dict, set, bytearray


Immutable: Cant change once created.
str, int, float, complex, tuple, Unicode( str for python3, represent in text)
note: once we the do add opration on str, they create the new string. for data in container:
str_final+=str(data)

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:

# for single line


multiple lines , multiple\s line
a. Difference between single cote and double cotes
i. Almost same, coding style. Double code means user might see it. Single code
strings are related to functions.

Multiple statement in one line


Import sys; a=10; b= 20; print a+b

LIST

Python list difference


o between append-vs-extend and insert
Append will add in end as full string between quotes abcdef
Extend will split string into characters a,b,c,d,e,f
o Pop and remove :
Remove removes the item by value and pop by index

l2.remove(abc) and l2.pop(3)


o Remove and del:
o count an element Occurrence of an element ls.count(a) or ls.count(1)
Find an index of an item
o To find all items:
Item_index = [ i for i,x in enumerate(list_name) if x ==item to be found]
o First occurrence:
Item_index = list_name.index(item to be fount)
Verify and item in list
o abc in list
Slice a list
o l[2:4]
o
l[2:]
o l[-1]the last element
o
l[::2] -> every second element
o
l.reverse() reorder the list element in reverse order
o l[::-1] print the list in reverse order but not reverse the string
randomly generated string of 4 element in the range of 1,100
o random.sample(range(1,100), 4)
Convert a list of string to int , l=[1,2,3,4]
o l = map(int,l)

Xrange not in python 3.0

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

Array - Store value of same type

My_array = array(I,[1,2,3,4])
Append, * ,insert,pop

Set (mutable):

How to setup item = set() # create an empty set


Or item = { 1,3,abc}
Collection of unique values.
o S1.add(ef), len(s1) => number of element,
o
ef in S1 Boolean value
o Print tu =>set([3, 4, 5, 23.89, 1.2, 'abc', 'efg'])
o Mutable, s1 = s2, change in s2 will reflect in s1. name is same object
S3 = s1.copy() will create a new set
Union = join two
Function=> add, remove, difference, intersection, ifsuperset, issubset
s1.difference_update(s2) = From s1 remove common item in s2

but has class as immutable (frozen set))

Tuple

Immutable, read only list


Create tu1 = ()
itemlist(1,2,3,a)
Cant add or remove
Len, tu1[3], tu1[4:], add two tuple and make new if wants to add anything, iteration, max, min,
len, cmp,

Dict(Mutable but keys are immutable, that is keyname cant change)

Hash type table


Key value pair
Create
o d1 = { key1:value1, k2:2,} Or
o d2= dict() will create an empty one OR
o
d3.fromkeys(d1) will have keys and value =None Or
o
d4.update(d1) => will have same value.
Functions :len(d1), str(d1), comp(d1,d2), type(d1)
Methods : d1.clear(), d1.copy(), , d1.keys(), d1.values(), d1.viewvalues(), d1.items()=> returns list
of two tuples, d1.setdefault(name)
D1.pop(name) and d1.popitem() => will take the first one out
D1.iteritems() gives you a pointer of object
D1.[name] = first key

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

Time, date, calendar


Pre defined
Import time .
What is ticks ==seconds from 1970 jan 1st, 12pm
time.localtime() gives local time in tuple
Time.ctime => time in string 'Tue Oct 18 16:26:18 2016'
time.gmtime() tuple time.struct_time(tm_year=2016, tm_mon=10, tm_mday=18
>>>time.strftime("%Y %m %d",ltime) '2016 10 18'
Time.sleep
Calendar
Import calendar
>>>cal = calendar.month(2016, 1)
>>> print cal
Datetime
Import datetime
>>>ctime = datetime.datetime.now()
>>>ctime.isoformat()
'2016-10-18T16:31:09.476000'

Format.

Print {:>10} .format(a). {:06.2f} , {1} {2}


print { 0 } and { 1 } .format(zero, eggs)
o zero and eggs
print {: d}.format((-23))
o get the negative number
'{:<30}'.format('left aligned')
o 'left aligned
'
'{:>30}'.format('right aligned')
o '
right aligned'
'{:^30}'.format('centered')
o '
centered
'
'{:*^30}'.format('centered')

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

uuid1()->it creates a UUID containing the computers network address


uuid4() creates a random UUID.

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 num in numbers


For I in range(1,2,19)

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

While True: loop


If() : elif and else
Although switch is not allowed in python, but we can use dict to bring out switch cases
def f(x):
return {
'a': 1,
'b': 2,
}.get(x, 9)

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

Try and finally


Try:
Try :
Finally:
Always run
Except IOError:

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,

class Contractor(Employee) # class inheritance


status = "temp"
print Employee.empCount # Print the current value
def displayCount(self) # function override
print in child
Employee.empCount = Employee.empCount+1

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

Socket reading data from page


o Lib socket, connect ( host,port), send( URL) , recv (datalength) , close
Import socket
mys = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mys.connect((www.google.com,80))
mys.send(GET http://.......\n\n)
data = mys.recv(512) ## put condition if len is less than 1 to close
mys.close()

URLlib , READ page like a FILE


Import urllib
Fhand = urllib.urlopen(http../redo.txt) = read image the same way. Urllib.urlopen(url).read()
for line in fhand:
print line.strip()
#You can find all links
Fh = urllib.url.open(url).read()
Links = re.findall(herf =(http://.*?,html)
Print links

For Mail
Import smtplib

Smltobj = smtplib.SMTP(mail.googl.com,25)
Smtlobj.sendmail(sender,reciver,mes)

Beautiful soup is lib-. That can extract tags etc

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

dir(str) == tell all method in class


help(str) documentation
Compile time error: when file method or code is used but not defined.
Zip : zip of the list and put is a tuple
Pass the reference: most by reference so it can change when calling function change it. Sometime,
immutable values can pass by value
Web-scarpy : extracting large amount of data from website. Ppython has urllib2, beacutifulsoup,
scrapy, pyquery,
With statement : file open, no need of close statement. With open(abc.txt, r) as file-handle: .
Output on screen (standred output) : import sys, file in write mode and redirect to screen
:Sys.stdout.write(line)
Explain split(), sub(), subn() methods of re module in Python
split() uses a regex pattern to split a given string into a list.
sub() finds all substrings where the regex pattern matches and then replace them with a different
string
subn() it is similar to sub() and also returns the new string along with the no. of replacements.
numpy =-> match array, scipy differential equation, metaplotlib -creat plots
tklnterlib for gui support
lamdba : a runtime constructor used by a function not bound by name
o Example g = lamdba x : x*2
g(2) will print 4
*args( for list), **kwargs(for disc): when a function dont know how many argument it will take,in
list and dict
o Def f(*args,**kwargs) : print(args, kwargs)
Self is a reference variable and an instance attribute that is used instead of the local variable
inside the class.
For virtual server ESXi/ESX import pysphere
Max(str) max alphabetic character