Wednesday, July 17, 2013

Google Python Class Day1


Copy & Paste Python codes from https://developers.google.com/edu/python/introduction

dir(sys)
help(sys)
help(sys.exit) 
help(len)

# Python Introduction
len('Hello')

# Python Program Hello.py
#!/usr/bin/python
import sys

def main():
    print 'Hello there', sys.argv[1]

if __name__ == '__main__':
    main()

# python hello.py Guido

# Modules and Imports
import sys
sys.exit(0)

# Python Strings
a = 'HELLO "poor" and '
b = "Too fancy ''"
c = "\* little"

a.lower()
b.upper()
a.fine('e')

#make copy
b=a[:]

b.append(10)
a.pop(10)
del a
del b[1]

# String Slices
s = 'Hello'
print s[:]
print s[1:3]
print s[-3:]

text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
print text

# Strings (Unicode)
ustring = u'A unicode \u018e string \xf1'
ustring
s = unistring.encode('utf-8')
print s
t =  unicode(s, 'utf-8')
print t

# If Statement
if speed >= 80: print 'You are so busted'
else: print 'Have a nice day'

# Python Lists
a = [4,2,3,1]
sorted(a)

# FOR and IN
result = []
for s in a: result.append(s)

s = 'this is a string'
for c in s:
       if c == 's': continue
       print c,
      
print '\n'
  
for c in s:
        if c == 's': break
        print c,
  
for c in s:
        print c,
    else:
        print 'else'
  
i= 0
while i < len(s):
        print s[i],
        i +=1
  else:
        print 'else'

# Range
range(20)
for i in range(20): print i

# Python Sorting
a =['aaaa', 'bbb', 's', 'bb']
sorted(a, key=len, reverse=True)
b=':'.join(a)
b.split(':')

# Tuples
(1,2,3)
(x,y) = (1,2)
a = [(1,"b"), (2,"a"), (1,"a")]
sorted(a)

# Python Dict
d = {}
d['a'] = 'alpha'
d['o'] = 'omega'
d['g'] = 'gamma'

d.get('s')
d.get('a')

'a' in d

d.keys()
d.values()
d.items()

for k in sorted(d.keys()): print 'key:', k, '->', d[k]
for k in d.items(): print k

# Del
var = 6
del var  # var no more!
 
list = ['a', 'b', 'c', 'd']
del list[0]    
del list[-2:]
print list     

dict = {'a':1, 'b':2, 'c':3}
del dict['b']  
print dict     

# Files
f = open('foo.txt', 'rU')
for line in f: 
   print line,   
f.close()

No comments:

Post a Comment