In [1]:
a  = 3

In [2]:
a


Out[2]:
3

In [3]:
ary = [1,2,3,4,5]
print ary[0]
print ary[-1]


1
5

In [7]:
name = ['John', 'May', 'David', 'Marry', 'Qoo']
age = [23,25,18,28,3]

cnt = 0
for n in name:
    if n == 'Qoo':
        print n, age[cnt]
    cnt += 1


Qoo 3

In [56]:
name = ['John', 'May', 'David', 'Marry', 'Qoo']
age = [23,25,18,28,3]


print  enumerate(name)
for idx, n in enumerate(name):
    if n == 'Qoo':
        print n, age[idx]
        
for idx, n in  enumerate(name):
    print idx, n


<enumerate object at 0x10e545280>
Qoo 3
0 John
1 May
2 David
3 Marry
4 Qoo

In [9]:
# list => [] , dictionary = {}
dic = {}
dic ={'a': 1, 'b': 'hello world'}
print dic['b']


hello world

In [11]:
student = {'John':23, 'May':25, 'David':18, 'Marry':28, 'Qoo':3}

print student['Qoo']


3

In [15]:
#declare dictionary
dic = {'a':100, 'b':"yes", 'c':0.98} 
print dic


{'a': 100, 'c': 0.98, 'b': 'yes'}

In [17]:
#get keys in dictionary
print dic.keys()
key = dic.keys()
key.sort()
print key


['a', 'c', 'b']
['a', 'b', 'c']

In [19]:
print 'a' in dic 
print 'd' in dic


True
False

In [20]:
#get values in dictionary
print dic.values() #get value of given key


[100, 0.98, 'yes']

In [21]:
print dic['a']


100

In [22]:
#get value of given key
print dic.get('a')


100

In [24]:
print dic
print dic['d']


{'a': 100, 'c': 0.98, 'b': 'yes'}
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-24-0ca2776588a5> in <module>()
      1 print dic
----> 2 print dic['d']

KeyError: 'd'

In [25]:
print dic.get('d')


None

In [27]:
try:
    print dic['d']
except KeyError as detail:
    print "keyerror", detail


keyerror 'd'

In [28]:
if 'd' in dic:
    print dic['d']

In [29]:
print dic.get('d' , 'D is not there')


D is not there

In [30]:
print dic.get('a' , 'D is not there')


100

In [33]:
print dic
dic['d'] = 123
print dic
dic['qoo'] = 789
print dic


{'a': 100, 'c': 0.98, 'b': 'yes', 'd': 123}
{'a': 100, 'c': 0.98, 'b': 'yes', 'd': 123}
{'a': 100, 'qoo': 789, 'c': 0.98, 'b': 'yes', 'd': 123}

In [34]:
dic.update({'e':123})
print dic


{'a': 100, 'c': 0.98, 'b': 'yes', 'e': 123, 'd': 123, 'qoo': 789}

In [36]:
dic.update({'e':123, 'f':234, 'g':456, 'h': 'qoo'})
print dic


{'a': 100, 'c': 0.98, 'b': 'yes', 'e': 123, 'd': 123, 'g': 456, 'f': 234, 'qoo': 789, 'h': 'qoo'}

In [37]:
dic['a'] = "revise a"
print dic


{'a': 'revise a', 'c': 0.98, 'b': 'yes', 'e': 123, 'd': 123, 'g': 456, 'f': 234, 'qoo': 789, 'h': 'qoo'}

In [41]:
for key in dic:
    print key, dic[key]


a revise a
c 0.98
b yes
e 123
d 123
g 456
f 234
qoo 789
h qoo

In [47]:
a = [1,2,1,1,3,4,1,2,3,6,1,2,1,3,2,1]
print a
a.sort()
print a

current = 0 
for ele in a:
    if ele != current:
        if current != 0 :
            print current, cnt
        current = ele
        cnt = 1
    else:
        cnt +=1
print current, cnt


[1, 2, 1, 1, 3, 4, 1, 2, 3, 6, 1, 2, 1, 3, 2, 1]
[1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 6]
1 7
2 4
3 3
4 1
6 1

In [49]:
a = [1,2,1,1,3,4,1,2,3,6,1,2,1,3,2,1]
dic = {}
for ele in a:
    if ele in dic:
        dic[ele] = dic[ele] + 1
    else:
        dic[ele] = 1

for ele in dic:
    print ele, dic[ele]


1 7
2 4
3 3
4 1
6 1

In [50]:
#def func(x):
#    return {}


a = [1,2,3]
for ele in a:
    if ele == 1:
        print 'first'
    elif ele == 2:
        print 'second'
    else:
        print 'last'
'''
switch(ele):
    case 1:
        print 'first'
    case 2:
        print 'second'
    defialt:
        print 'last'
'''


first
second
last
Out[50]:
"\nswitch(ele):\n    case 1:\n        print 'first'\n    case 2:\n        print 'second'\n    defialt:\n        print 'last'\n"

In [55]:
def func(x):
    return {1: 'first', 2: 'second'}.get(x)

print func(1)
print func(2)
print func(3)


first
second
None

In [54]:
def func(x):
    return {1: 'first', 2: 'second'}.get(x, 'last')

print func(1)
print func(2)
print func(3)


first
second
last

In [62]:
class Person():
    count = 0 # Static/class variable 
    def __init__(self, name, city):
        self.name = name # Variable for the instance 
        self.city = city 
        # Variable for the instance 
        Person.count += 1
    def number_of_persons(self): 
        return Person.count
    
First = Person("David", "Chiayi") 
First.number_of_persons() # 1


Out[62]:
1

In [63]:
Second = Person("QOO", "coca-cola") 
Second.number_of_persons() # 2


Out[63]:
2

In [66]:
print First.name
print Second.name


David
QOO

In [75]:
class MyInteger():
    def __init__(self, integer):
        print "constructor"
        self.integer = integer
    def __add__(self, integer): # Overloaded '+' operator
        if self.integer == 2 and integer == 2: 
            return 5
        else:
            return self.integer + integer
a = MyInteger(2)
print a
print dir(a)


constructor
<__main__.MyInteger instance at 0x10e4e8e60>
['__add__', '__doc__', '__init__', '__module__', 'integer']

In [68]:
print a + 2


5

In [69]:
print a + 3


5

In [76]:
class MyInteger():
    def __init__(self, integer):
        print "constructor"
        self.integer = integer
        
    def __str__(self):
        return str(self.integer)        
    
    def __add__(self, integer): # Overloaded '+' operator
        if self.integer == 2 and integer == 2: 
            return 5
        else:
            return self.integer + integer
a = MyInteger(2)
print dir(a)
print a


constructor
['__add__', '__doc__', '__init__', '__module__', '__str__', 'integer']
2

In [95]:
class Vehicle():
    '''
       help vehicle
    '''
    def my_own(self): 
        return True
    
class Bicycle(Vehicle):
    def __init__(self, color): 
        self.color = color 
    def has_wheels(self): 
        return True
    
class rent_bike(Bicycle):
    def my_own(self): 
        return False
    
v = Vehicle()
print dir(v)
#print help(v)


b = Bicycle('red')
print dir(b)
print b.my_own()

ubike = rent_bike('yellow')
print dir(ubike)
print ubike.my_own()
print ubike.color


['__doc__', '__module__', 'my_own']
['__doc__', '__init__', '__module__', 'color', 'has_wheels', 'my_own']
True
['__doc__', '__init__', '__module__', 'color', 'has_wheels', 'my_own']
False
yellow

In [96]:
print ubike


<__main__.rent_bike instance at 0x10e4eeea8>

In [99]:
class rent_bike(Bicycle):
    def __str__(self): 
        return "my bike is " + self.color     
    def my_own(self): 
        return False

In [100]:
ubike = rent_bike('yellow')

print ubike


my bike is yellow

In [103]:
class Vehicle():
    def my_own(self): return True
class Bicycle(Vehicle):
    def __init__(self, color): self.color = color
    def has_wheels(self): return True
    def __str__(self): return "%s is %s"%(self.__class__.__name__,self.color)
class rent_bike(Bicycle):
    def my_own(self): return False
    
Ubike = rent_bike('yellow') 
print Ubike


rent_bike is yellow

In [104]:
#Writing Hello World Into test.txt
fid = open('test.txt', 'w') 
fid.write('Hello\nWorld') 
fid.close()

In [111]:
fid = open('test.txt', 'r')
for line in fid: # Using file identifier as iterator
    print line.strip()
    print("Line: " + line.strip()) 
fid.close()


Hello
Line: Hello
World
Line: World

In [110]:
fid = open('test.txt', 'r')
s = fid.read() # Read the entire file fid.close()
print "<head>" + s + "</head>"


<head>Hello
World</head>

In [113]:
fid = open('test.txt') 
k=0
for line in fid:
    k=k+1 
print(k)
fid.close()


2

In [117]:
print [line for line in open('test.txt')]


['Hello\n', 'World']

In [118]:
ary = []
fid = open('test.txt', 'r')
for line in fid:
    ary.append(line)
print ary


['Hello\n', 'World']

In [119]:
a = [1,2,3,4,5]
print len(a)
print len([line for line in open('test.txt')])


5
2

In [121]:
f = open('cnn.txt', 'r')
for line in f:
    #print line.strip()
    pass # please mark this one and unmark last line
f.close()

In [136]:
# read text from file cnn.txt
f = open('cnn.txt', 'r')
lines = f.read()
f.close()

# stat the occurance of each word
dic = {}
for word in lines.split():
    if word in dic:
        dic[word] += 1
    else:
        dic[word] = 1

# print out dictionary
#for ele in dic:
#    print ele, dic[ele]

#print dic.items()


import operator
sorted_x = sorted(dic.items(), key=operator.itemgetter(1), reverse=True) 
#print sorted_x
#print sorted_x[0:10]
#print sorted_x[10:30]


for x in sorted_x[0:10]:
    #print x
    print x[0], x[1]


('the', 30)
the 30
('in', 13)
in 13
('of', 12)
of 12
('and', 11)
and 11
('on', 10)
on 10
('a', 9)
a 9
('engine', 9)
engine 9
('to', 8)
to 8
('said', 5)
said 5
('was', 5)
was 5

In [138]:
a = [1,2,3,4,5]
a.append(6)
print a
print dir(a) #list


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

In [140]:
a= (1,2,3,4,5)
print dir(a) # tuple
a.append(6)


['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-140-7f538fc09316> in <module>()
      1 a= (1,2,3,4,5)
      2 print dir(a)
----> 3 a.append(6)

AttributeError: 'tuple' object has no attribute 'append'

In [142]:
a= (1,2,3,4,5)
print a[0]
a = list(a)
a.append(6)
print a


1
[1, 2, 3, 4, 5, 6]

In [ ]: