kcchung
kcchung@cs.nctu.edu.tw
https://url.fit/na-py-git
https://url.fit/na-py-slide
slide
example
Linux, FreeBSD, MacOSX
built-in
pkg install python
$ python na.py
$ python -c 'print "NA score: 100"'
$ python -m SimpleHTTPServer 8888
#! /usr/bin/env python
# -*- coding: utf8 -*-
# file: na.py
def na(score=None):
if score:
return 'NA score: %s' % score
else:
return 'failed.'
if __name__ == '__main__':
import sys
if len(sys.argv) >= 2:
print na(sys.argv[1])
else:
print na()
shebang
encoding
comment
starts a block
4-space indent
__name__ : name of the module
>>> help('for')
'''
The "for" statement
*******************
The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
The expression list is evaluated once; it should yield an iterable
object. An iterator is created for the result of the
"expression_list". The suite is then executed once for each item
provided by the iterator, in the order returned by the iterator. Each
item in turn is assigned to the target list using the standard rules
for assignments (see *Assignment statements*), and then the suite is
executed. When the items are exhausted (which is immediately when the
sequence is empty or an iterator raises a "StopIteration" exception),
the suite in the "else" clause, if present, is executed, and the loop
terminates.
A "break" statement executed in the first suite terminates the loop
without executing the "else" clause's suite. A "continue" statement
executed in the first suite skips the rest of the suite and continues
with the next item, or with the "else" clause if there is no next
item.
The for-loop makes assignments to the variables(s) in the target list.
This overwrites all previous assignments to those variables including
those made in the suite of the for-loop:
for i in range(10):
print(i)
...
'''
>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__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', 'clear', 'copy', 'count', 'extend',
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> from pprint import pprint
>>> pprint(dir([]))
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__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',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_numeric.py
print type(1) # <type 'int'>
print type(0.1) # <type 'float'>
print type(6 + 2j) # <type 'complex'>
print 1 + 2 * 3 # 7
print 5 / 2 # 2
print 5 / 2.0 # 2.5
print 2 ** 3 # 8
print 2 ** 100 # 1267650600228229401496703205376L
print 2 ** 0.5 # 1.4142135623730951
print abs(-12345) # 12345
print round(math.pi, 3) # 3.142
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_numeric.py
import math
print math.e * math.pi # 8.539734222673566
print math.floor(1.5) # 1.0
print math.ceil(1.5) # 2.0
print 0b101 | 0b10 # 7
print 1 << 5 # 32
print int('20') # 20
print int('0xF', base=16)# 15
print hex(256) # '0x100'
print oct(256) # '0400'
print bin(256) # '0b100000000'
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_list_tuple.py
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#idx 0 1 2 3 4 5 6 7 8 9
# -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print type([]) # <type 'list'>
print type(()) # <type 'tuple'>
print 7 in a # True
print 100 in a # False
print 'c' in 'nctu' # True
print c # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 100]
b = [100] * 5
print b # [100, 100, 100, 100, 100]
print b.count(100) # 5
c = a + [100, 100]
print c # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 100]
# a[start:stop:step]
print a[2] # 3
print a[-2] # 9
print a[2:7] # [3, 4, 5, 6 ,7]
print a[2:7:2] # [3, 5, 7]
print a[:3] # [1, 2, 3]
print [6:] # [7, 8, 9, 10]
print [::3] # [1, 4, 7, 10]
print [::-1] # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_list_tuple.py
b = [100] * 5
b.append(7)
print b # [100, 100, 100, 100, 100, 7]
b.pop()
print b # [100, 100, 100, 100, 100]
b.append([-1])
print b # [100, 100, 100, 100, 100, [-1]]
b.extend([7, 8])
print b # [100, 100, 100, 100, 100, [-1], 7, 8]
b.insert(0, 7788)
print b # [7788, 100, 100, 100, 100, 100, [-1], 7, 8]
(x, y) = (4, 5)
x, y = 4, 5
print x, y # 4, 5
x, y = y, x # swap
print x, y # 5, 4
a = [i for i in range(10)]
print a # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [i**2 for i in a]
print b # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
c = [i for i in b if i % 2 == 0]
print c # [0, 4, 16, 36, 64]
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_string.py
print type('') # <type 'str'>
s = 'NA is very interesting.'
print 'NA' in s # True
print s[6:9] # 'ver'
print s[::-1][1:10:3].upper()
s.replace('NA is', 'NA is not')
print s # 'NA is not very interesting.'
print s.split() # ['NA', 'is', 'very', 'interesting.']
print '\t\t\t\t\t www.porn.com \t\t\t'.strip()
print ', '.join('abc') # 'a, b, c'
# 告白用
print '<3'.join(['I', 'love', 'you']) # 'I<3love<3you'
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_string.py
print '{0} {1} {2}'.format('a', 'b', 'c') # 'a b c'
print '{} {} {}'.format('a', 'b', 'c') # 'a b c'
print '{1} {2} {0}'.format('a', 'b', 'c') # 'b c a'
print 'Meet me at ({x}, {y}) on 3pm.'.format(x=24.787724, y=120.997618)
Frozen Set
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_dict.py
print type({}) # <type 'dict'>
print type(dict()) # <type 'dict'>
user = {'name': 'ToolMan', 'gender': 'Male', 'age': 20, 'height': 175, 'weight': 70, 'girlfriend': None}
# user = dict(name='ToolMan', gender='Male', age=20, height=175, weight=70, girlfriend=None)
print len(user) # 6 items
print user['name'] # 'ToolMan'
print 'gender' in user # True
user['girlfriend'] = 'LeftHand'
print user # {'name': 'ToolMan', 'gender': 'Male', 'age': 20, 'height': 175, 'weight': 70, 'girlfriend': 'LeftHand'}
print user.keys() # ['name', 'weight', 'gender', 'age', 'height', 'girlfriend']
print user.values() # ['ToolMan', '70', 'Male', 19, '175', None]
print user.items() # [('name', 'ToolMan'), ('weight', '70'), ('gender', 'Male'), ('age', 19), ('height', '175'), ('girlfriend', None)]
for key, value in user.items():
print key, value
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_dict.py
print type({}) # <type 'dict'>
print type(dict()) # <type 'dict'>
user = {'name': 'ToolMan', 'gender': 'Male', 'age': 20, 'height': 175, 'weight': 70, 'girlfriend': None}
# user = dict(name='ToolMan', gender='Male', age=20, height=175, weight=70, girlfriend=None)
print len(user) # 6 items
print user['name'] # 'ToolMan'
print 'gender' in user # True
user['girlfriend'] = 'LeftHand'
print user # {'name': 'ToolMan', 'gender': 'Male', 'age': 20, 'height': 175, 'weight': 70, 'girlfriend': 'LeftHand'}
print user.keys() # ['name', 'weight', 'gender', 'age', 'height', 'girlfriend']
print user.values() # ['ToolMan', '70', 'Male', 19, '175', None]
print user.items() # [('name', 'ToolMan'), ('weight', '70'), ('gender', 'Male'), ('age', 19), ('height', '175'), ('girlfriend', None)]
for key, value in user.items():
print key, value
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_set.py
print type(set()) # <type 'set'>
attractions = {"湯圍溝溫泉公園", "蘭陽博物館", "頭城和平老街"}
attractions.add("礁溪戶政事務所")
attractions.add("橘之鄉蜜餞形象館")
...
attractions.add("橘之鄉蜜餞形象館")
l = ['樂山拉麵', '火車站阿伯蔥油餅']
gf_attractions = set(l)
attractions = attractions | gf_attractions # 這樣就不會被罵了
attractions.remove("礁溪戶政事務所")
print attractions # 看不懂
for attraction in attractions:
print attraction
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_none.py
print type(None) # <type 'NoneType'>
a = None
print a is None # True
print '100' is not None # True
if condition:
print 'Hang out with me!'
else:
print 'bye'
# | means OR, not an operator.
condition = None | False | [] | '' | {} | set() | 0 | 0.0
if
if condition_1:
# do something
elif condition_2:
# do something
elif condition_3:
# do something
else:
# do something
for
for item in iterable:
# do something
while
while expression:
# do something
break,continue,pass
Loop:
if condition:
break
if condition:
continue
if condition:
pass
break,continue,pass
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_break_continue_pass.py
import random
while True:
value = random.randint(0, 99)
if value % 24 == 0:
print 'My parents are not home.'
break
Loop:
# do something
else:
# do something
else
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_else.py
homeworks = ['na_%s' % str(i) for i in range(1,50)]
for homework in homeworks:
do_your_homework()
else:
tell_mom()
else
try:
# do something
except SomeError:
# do something
except SomeAnthorError:
# do something
else:
# do something
finally:
# do something
try
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_try.py
import MySQLdb
try:
db = MySQLdb.connect(host="localhost", user="root", passwd="db_pass", db="db_name")
except Exception as e:
print e
else:
cursor = db.cursor()
cursor.execute('select * from table')
rows = cursor.fetchall()
finally:
db.close()
try
def function(x, y=2):
return x, y
def function(*args):
return args
def function(**kargs):
return kargs
def
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_def.py
def fib2(n):
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
def
print
print 'Hello, world'
# Hello, world
print "Hi I'm %s" % 'jay'
# Hi i'm jay
print 'What\'s up?'
# What's up?
print 'See', 'you', 'soon'
# See you soon
raw_input
'''
raw_input([prompt])
'''
price = raw_input("How much?")
print "It's " + price
print "It's " + price*0.7 # invalid
print "It's " + int(price)*0.7
open
'''
file object = open(file_name
[, access_mode]
[, buffering]
)
'''
fin = open('/etc/rc.conf', 'r')
content = fin.read()
fin.close()
with open('/etc/rc.conf', 'r') as fin:
for line in fin:
print line
# file is automatically closed
import
# standard library
import math
# a python file(na.py) as a module
import na
from pprint import pprint
pprint(dir(math))
pip
# https://bootstrap.pypa.io/get-pip.py
python get-pip.py
csv
#! /usr/bin/env python
# -*-coding: utf8 -*-
# file: na_csv.py
import csv
with open('file.csv', 'r') as fin:
for line in csv.reader(fin):
print line
os.path
#! /usr/bin/env python
# -*-coding: utf8 -*-
# file: na_os_path.py
import os
def list_paths(path):
paths = []
for dir_path, dir_names, file_names in os.walk(path):
for file_name in file_names:
paths.append(os.path.join(dir_path, file_name))
return paths
if __name__ == '__main__':
target = '/etc'
for path in list_paths(target):
print path
re
#! /usr/bin/env python
# -*-coding: utf-8 -*-
# file: na_re_search.py
import re
timestamp = 'Sun Mar 24 21:34:34 CST 2016'
r = re.search('\d+:\d+:\d+', timestamp)
print '{}-{} matched: {}'.format(r.start(), r.end(), r.group(0))
r = re.search('(\d+):(\d+):(\d+)', timestamp)
print 'hour=%s, minute=%s, second=%s' % (r.group(1), r.group(2), r.group(3))
re
#! /usr/bin/env python
# -*-coding: utf-8 -*-
# file: na_re_split_findall.py
import re
timestamp = 'Sun Mar 24 21:34:34 CST 2016'
r = re.split('\W', timestamp)
print r
# ['Sun', 'Mar', '24', '21', '34', '34', 'CST', '2016']
r = re.findall('\w+s', 'raining cats & dogs')
print r
# ['cats', 'dogs']
*requests
#! /usr/bin/env python
# -*-coding: utf-8 -*-
# file: na_requests.py
import re
import requests
url = 'https://www.ptt.cc/bbs/Gossiping/M.1456150026.A.855.html'
r = requests.get(url)
print r.text
'''
<div class="bbs-screen bbs-content center clear">
<form action="/ask/over18" method="post">
<input type="hidden" name="from" value="/bbs/Gossiping/M.1456150026.A.855.html">
<button class="btn-big" type="submit" name="yes" value="yes">我同意,我已年滿十八歲<br><small>進入</small></button>
<button class="btn-big" type="submit" name="no" value="no">未滿十八歲或不同意本條款<br><small>離開</small></button>
</form>
</div>
'''
*requests
#! /usr/bin/env python
# -*-coding: utf-8 -*-
# file: na_requests.py
import re
import requests
url = 'https://www.ptt.cc/bbs/Gossiping/M.1456150026.A.855.html'
r = requests.get(url, cookies={'over18': '1'})
import re
title = re.findall('<title>(.*?)</title>', r.text)[0]
print title
# [問卦] 台大如果有妹妹系要幾級分? - 看板 Gossiping - 批踢踢實業坊
subprocess
#! /usr/bin/env python
# -*-coding: utf-8 -*-
# file: na_subprocess_call.py
import subprocess
return_code = subprocess.call(['ls', '-al'])
print return_code
# 0
subprocess
#! /usr/bin/env python
# -*-coding: utf-8 -*-
# file: na_subprocess_check_ouput.py
import subprocess
output = subprocess.check_output(['ls', '-al'])
print output
'''
total 4148360
drwxr-xr-x+ 36 jaychung staff 1224 2 22 13:55 .
drwxr-xr-x+ 81 jaychung staff 2754 2 22 21:54 ..
-rwxr-xr-x@ 1 jaychung staff 8196 2 1 15:39 .DS_Store
-rwxr-xr-x 1 jaychung staff 0 2 7 2015 .localized
-rw-r-----@ 1 jaychung staff 1517152 12 11 12:42 416308.pdf
-rw-r-----@ 1 jaychung staff 4173323 11 5 21:14 OReilly.Web.Scraping.with.Python.2015.6.pdf
-rw-r-----@ 1 jaychung staff 896727 12 23 10:41 WWW簡介.pdf
drwxr-xr-x 18 jaychung staff 612 1 19 21:38 api
drwxr-xr-x 11 jaychung staff 374 2 19 20:32 cscc
-rw-r--r--@ 1 jaychung staff 296703 11 25 12:39 dooooor.pdf
-rw-r--r--@ 1 jaychung staff 28893 12 21 17:55 fb.jpg
drwxr-xr-x@ 11 jaychung staff 374 11 10 15:23 garand-sticky-1643193
-rw-r--r--@ 1 jaychung staff 396752 12 23 10:16 msdn.key
-rw-r-----@ 1 jaychung staff 234165 7 13 2015 multigon_3d_wallpaper_by_momkay-wallpaper-1440x900.jpg
-rw-r--r-- 1 jaychung staff 170 2 22 21:54 na_os_path.py
-rw-r--r--@ 1 jaychung staff 793579 2 19 21:55 na_python_prog.key
drwx------@ 6 jaychung staff 204 12 23 16:48 neon-bootstrap-admin-theme
drwxr-xr-x 27 jaychung staff 918 1 7 14:49 recommender-letter
-rw-r-----@ 1 jaychung staff 4392933 11 18 10:56 shutterstock_219087994.jpg
drwxr-xr-x@ 13 jaychung staff 442 9 15 06:23 smooth-scroll-master
drwxr-xr-x 7 jaychung staff 238 1 4 16:23 temp
drwxr-xr-x 18 jaychung staff 612 2 12 01:23 urlfit
-rw-------@ 1 jaychung staff 165 1 13 23:33 ~$Hw6_LDAP Puppet Jail.pptx
-rw-------@ 1 jaychung staff 162 10 31 01:52 ~$PP-Homework-1.docx
-rw-------@ 1 jaychung staff 171 11 24 20:48 ~$unique_count_ingredients.xlsx
-rw-r--r--@ 1 jaychung staff 283498 12 20 21:52 螢幕快照 2015-12-20 下午9.52.28.png
-rw-r--r--@ 1 jaychung staff 288724 12 20 21:52 螢幕快照 2015-12-20 下午9.52.42.png
-rw-r--r--@ 1 jaychung staff 158020 1 31 19:31 螢幕快照 2016-01-31 下午7.31.40.png
-rw-r--r--@ 1 jaychung staff 157932 1 31 19:33 螢幕快照 2016-01-31 下午7.33.33.png
-rw-r--r--@ 1 jaychung staff 97399 2 3 19:07 螢幕快照 2016-02-03 下午7.07.41.png
-rw-r--r--@ 1 jaychung staff 123172 2 3 19:13 螢幕快照 2016-02-03 下午7.13.23.png
-rw-r--r--@ 1 jaychung staff 1640994 2 4 20:42 螢幕快照 2016-02-04 下午8.42.35.png
-rw-r--r--@ 1 jaychung staff 665149 2 19 23:19 螢幕快照 2016-02-19 下午11.19.38.png
-rw-r--r--@ 1 jaychung staff 94652 2 19 00:41 螢幕快照 2016-02-19 上午12.41.21.png
-rw-r--r--@ 1 jaychung staff 2039989033 2 20 13:52 万万没想到.Surprise.2015.HD1080P.X264.AAC.mp4
-rw-r-----@ 1 jaychung staff 67658436 11 5 21:07 基于开源工具的数据分析.pdf
'''
subprocess
#! /usr/bin/env python
# -*-coding: utf-8 -*-
# file: na_subprocess_popen.py
import subprocess
process = subprocess.Popen(
['base64', '-D'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
output = process.communicate(input=b'cHl0aG9uCg==')[0]
print output
# 'python\n'
socket
#! /usr/bin/env python
# -*-coding: utf-8 -*-
# file: na_socket_server.py
import socket
HOST = ''
PORT = 50007
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(1)
conn, addr = sock.accept()
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
conn.close()
socket
#! /usr/bin/env python
# -*-coding: utf-8 -*-
# file: na_socket_client.py
import socket
HOST = ''
PORT = 50007
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
sock.sendall('Hello, world')
data = sock.recv(1024)
sock.close()
print "Received: " + str(data)
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_oop.py
class Employee(object):
''' Employee class '''
def __init__(self, name, age, salary):
self._name = name
self._age = age
self._salary = salary
self._expired_at = None
def __repr__(self):
return '<Employee name={} age={} salary={} expired_at={}>'.format(
self._name, self._age, self._salary, self._expired_at
)
if __name__ == '__main__':
me = Employee('kcchung', 22, 5000)
me._salary = 10000
print me
inheritance
self is required
_var : public
__var : private
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_oop_1.py
class Employee(object):
''' Employee class '''
__company = 'NCTU'
__boss = ['Mike', 'Alice', 'Bob']
def __init__(self, name, age, salary):
self._name = name
self._age = age
self._salary = salary
self._expired_at = None
def annual_salary(self):
return self._salary * 13.5
@staticmethod
def check_boss(name):
if name in Employee.__boss:
print '{} is one of our boss.'.format(name)
else:
print '{} is not one of our boss.'.format(name)
@classmethod
def visit(cls, name):
print 'Hi {}, you are now at {}.'.format(name, cls.__company)
def __repr__(self):
return '<Employee name={} age={} salary={} expired_at={}>'.format(
self._name, self._age, self._salary, self._expired_at
)
if __name__ == '__main__':
me = Employee('kcchung', 22, 5000)
me.visit('jay')
Employee.check_boss('kcchung')
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_oop_2.py
class Employee(object):
''' Employee class '''
__company = 'NCTU'
__boss = ['Mike', 'Alice', 'Bob']
def __init__(self, name, age, salary):
self._name = name
self._age = age
self._salary = salary
self._expired_at = None
def annual_salary(self):
return self._salary * 13.5
@staticmethod
def check_boss(name):
if name in Employee.__boss:
print '{} is one of our boss.'.format(name)
else:
print '{} is not one of our boss.'.format(name)
@classmethod
def visit(cls, name):
print 'Hi {}, you are now at {}.'.format(name, cls.__company)
def __repr__(self):
return '<Employee name={} age={} salary={} expired_at={}>'.format(
self._name, self._age, self._salary, self._expired_at
)
class Manager(Employee):
''' NCTU Manager '''
def __init__(self, name, age, salary, group):
super(Manager, self).__init__(name, age, salary)
self._group = group
# overide
def annual_salary(self):
return self._salary * 20
def __repr__(self):
return '<Manager name={} age={} salary={} expired_at={} group={}>'.format(
self._name, self._age, self._salary, self._expired_at, self._group
)
if __name__ == '__main__':
me = Manager('kcchung', 22, 10000, 'www')
print me.annual_salary()
├── example.py
├── module_a.py
└── package
├── __init__.py
├── module_b.py
└── module_c.py
1 directory, 5 files
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: example.py
import module_a
print module_a.name # module_a
import package.module_b
package.module_b.na() # This is na function.
from package import module_c
print module_c.name # module_c
>>> 1 + '1'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file: na_lambda.py
f = lambda x, y: x if x > y else y
print f(2, 3) # 3
d = {'a': 200, 'b': 400, 'd': '50'}
keys = d.keys()
keys.sort(key=lambda x: d[x], reverse=True)
for key in keys:
print key, d[key]