2. 파이썬 설치
• 강의 전 아래 웹사이트에서 파이썬 프로그램을 다운
로드 받아 설치해주세요.
• http://www.python.org
• Download “Python 2.7.3 Windows Installer”
• 설치 후, ;C:Python27 를 PATH 환경변수에 추가
4. 앞서가는 생물정보 분석
• 머리속의 아이디어를 빠르게 구현
• Battery included. 이미 만들어진 라이브러리 이용
• Prototype Product
5. 교육 구성
• 기본문법 • 기본 실습문제
– Python introduction – 구구단 함수
– Data type – 이차방정식 근의 공식
– Control flow – 단어빈도수 계산
– Function, Module, Package
– String formatting
• 객체지향과 고급기능 • 객체지향 문제
– Exception and Test – FASTA 서열 다루기
– Class
– Decorator, Iterator, Generator
– Standard libraries
9. Computer language
• Information is a sequence (order)
• How can we manage it?
• Computer language is for it by mimic human’s language
• History
– Machine language
– Assembly
– Compiled language (C,…)
– Interpreter language
(Java, Python,…)
10. Operating System
• Unix (linux)
• MS-Windows
• Mac OS X
• Python runs everywhere
11. What is Python?
• 1991’s Guido Van Rossum
• Free and Open source
• For easy language
• Object oriented scripting
• Dynamic typing
• Interpreter
• Glue language
12. Why Python?
• Easy object oriented
• Easy to learn
• Prototyping
• Battery included
• Portable
• Extensible
• Powerful internal data structure
21. Numeric types
• int, long, float, complex
• +, -, *, /, //, %, **
• Builtin functions : abs, divmod, pow
• For advanced calculation, use import math
22. Integer and Long
• Integer and long literal
– ~L : Long
– 0b~ : 2진수(bin) : 0b101 5
– 0o~ : 8진수(oct) : 011 9
– 0x~ 16진수(hex) : 0xa 10
• Long merged to int in python3
23. Float
• 3.14 10. .001 1e100 3.14e-10 0e0
• Builtin functions : round
• Float is not precise number
• Use Decimal but it is slow
25. Method?
• In Python, all is object
• Object has attributes. Use “.” for access
• Some attribute is method. Use “()” for call
• a = 27
• dir(a)
• help(a)
• a.real
• a.imag
• a.conjugate()
28. String
• It is a byte stream
• Methods : capitalize, center, count, endswith, startswith, find,
index, join, strip, split, zfill
• Bach slash is special
– n : ASCII linefeed
– t : ASCII horizontal tab
• String literals
– r~ : raw string (back slash is not escaping)
– u~ : unicode
29. Tuple
• Immutable sequence of anything
• Use “( )”
30. List
• Mutable sequence of anything, Use “[ ]”
31. Set
• Unordered collection of distinct hashable objects
• Mutability
– Mutable : set (add, remove)
– Immutable : frozenset
• Methods : union(|), intersection(&), difference(-),
symmetric_difference(^)
33. Dictionary
• Mapping object maps hashable values to arbitrary objects.
• Mutable
• Usages
– d = { key : value }
– d[key] = value
– key in d
– d.keys(), d.values(), d.items()
– d.update(annother_d)
34. Bool
• Boolean type
• True or False
• All python objects has boolean value
36. Scope
• 괄호 {} 대신 들여쓰기로 현
재 범위 규정
• 들여쓰기가 끝나면 해당
Scope 가 끝남을 의미
• 아무것도 안할 때는 pass
37. if statement
• bool() 함수로 평가하여, True, False 에 따라 분기
• elif, else 는 옵션
38. if statement
• Operator : >, <, >=, <=, !=, ==
• When string, alphabet order
• When sequence type, from first element
• When other types, number < dict < list < string < tuple
• hasattr
• belong check uses “in” statement : when dict, checks keys
default
• Same object check uses “is” statement
• None, 0, 0.0, “”, [], (), {} is False
39. Logical calculation
• not
• and, or
– True and True True
– True and False False
– False and False False
– False or False False
– True or False True
– It returns that value. So can use one line if statement
• if a: return b else: return c a and b or c
• all(), any()
40. for statement
• Repeat elements in sequence types data
41. for statement
• When dict
– keys(), values(), items()
– Default is keys()
• When list
– Use [:] copy when self alteration
45. break and continue statement
• break : breaks out the loop
• continue : next iteration of the loop
• else : end without break or continue
46. while statement
• Repeat while an
expression is true
• Used in break, continue,
else
47. Fibonacci series
• 어떤 사람이 벽으로 둘러싸인 어떤 곳에다 토끼 암수 한 쌍
을 집어 넣었다. 매달 한 쌍의 토끼가 태어나고 또 그 신생
토끼의 쌍이 두 달째부터 새끼를 낳을 수 있다면, 1년 뒤 원
래의 한 쌍으로부터 얼마나 많은 쌍의 토끼가 태어날까?
62. Python functional programming
• LISP, Heskel
• Function is an object
• Recursion
• Expression evaluation instead of statement
• It can be used in control flow
• In Python: map, reduce, filter, lambda, list comprehension
(,iterator, generator)
65. Module
A file containing Python definitions and statements.
The file name module name (.py)
In fib.py, fib, fib2 functions existed,
◦ from fib import fib, fib2
◦ fib(3)
or
◦ import fib
◦ fib.fib2(3)
or
◦ from fib import *
◦ fib(3)
66. import path
• That file is in current directory or PYTHONPATH
environmental variable
• Or
import sys
sys.path.append(‘/mydirectory’)
67. Module
Byte compile for Virtual Machine
◦ import statement search .pyc first.
◦ If .py is new, recompile it
◦ If use –O option (optimization), it makes .pyo
For reload, use reload(module)
If module was executed program mode, __name__ is
‘__main__’ but module importing, __name__ is module name
So, for scripting (not for importing), use
if __name__ == “__main__”:
fib(3)
68. Packages
• A way of structuring python module namespace by using
“dotted module names”
69. Packages
import sound.effects.echo
sound.effects.echo()…
Or
from sound.effects import echo
echo()…
Or
from sound.effects import echo as myecho
myecho()…
71. Functions for string
• str – 비형식적 문자열로 변환
• repr – 형식적 문자열로 변환
• eval – 문자열을 실행 (expression, 식)
• exec – 문자열을 실행 (statement, 문)
>>> s = 'Hello, world' >>> s1 = repr([1,2,3])
>>> str(s) >>> s1
'Hello, world' „[1, 2, 3]'
>>> repr(s) >>> eval(s1)
"'Hello, world'" [1, 2, 3]
>>> >>>
>>> str(0.1) >>> a = 1
'0.1' >>> a = eval(„a + 4‟)
>>> repr(0.1) >>> a
'0.10000000000000001' 5
>>> >>> exec „a = a + 4‟
>>> a
9
72. String formatting (old style)
>>> template = "My name is %s and I have %i won"
>>> template % ("yong", 1000)
'My name is yong and I have 1000 won'
>>>
>>> template = "My name is %(name)s and I have %(money)i won"
>>> template % {'name':'yong', 'money':1000}
'My name is yong and I have 1000 won'
>>>
>>> name = 'yong'
>>> money = 1000
>>> template % locals()
'My name is yong and I have 1000 won'
>>>
>>> import math
>>> print 'The value of PI is approximately %5.3f.' % math.pi
The value of PI is approximately 3.142.
>>>
74. String formatting (new style) 1
>>> template = "My name is {0} and I have {1} won"
>>> template.format("yong", 1000)
'My name is yong and I have 1000 won'
>>>
>>> template = "My name is {name} and I have {money} won"
>>> template.format(name=„yong', money=1000}
'My name is yong and I have 1000 won'
>>>
>>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
... other='Georg')
The story of Bill, Manfred, and Georg.
>>>
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print '{0:10} ==> {1:10d}'.format(name, phone)
...
Jack ==> 4098
Dcab ==> 7678
Sjoerd ==> 4127
75. String formatting (new style) 2
"First, thou shalt count to {0}" # References first positional argument
"My quest is {name}" # References keyword argument 'name'
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}" # First element of keyword argument
'players'.
"Harold's a clever {0!s}" # Calls str() on the argument first
"Bring out the holy {name!r}" # Calls repr() on the argument first
"A man with two {0:{1}}".format("noses", 10)
76. Reading and Writing Files
>>> f = open(„/tmp/workfile‟, „w‟)
>>> print f
<open file „/tmp/workfile‟, mode „w‟ at 80a0960>
• mode : ‘r’, ‘w’, ‘a’, ‘r+’, ‘b’, ‘rb’, ‘wb’
• Method : read, readline, readlines, write
>>> f.read() >>> f.readlines()
'This is the entire file.n' ['This is the first line of the file.n', 'Second
>>> f.read() line of the filen']
'„ >>>
>>> f.readline() >>> for line in f:
'This is the first line of the file.n' print line,
>>> f.readline() This is the first line of the file. Second line
'Second line of the filen' of the file
>>> f.readline() >>>
'' >>> f.write(str(43))
77. Position in the file
• f.tell() : current position
• F.seek(offset, from_what) : go there position
– from_what : 0 start, 1 current, 2 end
>>> f = open('/tmp/workfile', 'r+')
>>> f.write('0123456789abcdef')
>>> f.seek(5) # Go to the 6th byte in the file
>>> f.read(1)
'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
>>> f.read(1)
'd'
78. File close
• f.close() : close it and free up any system resource
• “with” keyword when free up
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
>>> with open('/tmp/workfile', 'r') as f:
... read_data = f.read()
>>> f.closed
True
79. Standard IO
• stdin, stdout, stderr
• Command line pipe “>”, “2>”, “<“, “|”
def work(input_file, output_file):
output_file.write("<")
output_file.write(input_file.read())
output_file.write(">")
work(open('a.txt'), open('b.txt', 'w'))
import sys
work(sys.stdin, sys.stdout)
-----
python a.py < a.txt > b.txt
• Different with sys.argv
80. StringIO
• Virtual file on memory
from cStringIO import StringIO
handle = StringIO("""
> test fasta
AGTCAGTC
AGTCCCCC
""")
for line in handle:
print line
86. Excersize
임의의 텍스트파일내 단어의 출현 빈도를 조사하여 가장 많
이 출현한 단어부터 정렬하여 출력하는 프로그램 (특수기호
제외, 소문자로 통일)
$ python word_frequency.py < input.txt
32 the
28 of
17 boy
…
87. Excersize
임의의 FASTA 형식의 파일에 저장된 DNA 서열을 읽어 GC
함량을 계산하시오 (single FASTA format)
$ python gc_content.py < input.fasta
0.55
88. Excersize
임의의 FASTA 형식의 파일에 저장된 DNA 서열을 읽어
Reverse complement 서열을 출력하시오 (Single FASTA)
$ python reverse_complement.py < input.fasta
> seq1 reverse complement
AGTCAAGGCCAAGTCCAA
AGCAGCAGGAGCCAAGGT
95. Handling Exceptions example
def dosomething():
a = 1/0
try:
dosomething()
except ArithmeticError:
print „Exception occurred‟
96. Raising Exceptions
• “raise” statement allows the programmer to force a specified
exception to occur.
97. User-defined Exceptions
• Programs may name their own exceptions by creating a new
exception class
98. Assert statement
• Usually, used when debugging
a = 30
margin = 2 * 0.2
assert margin > 10, „not enough margin %s‟ % margin
if not margin > 10:
raise AssertionException(„not enough margin %s‟ % margin)
99. Unit test 란?
• 프로그램을 작은 단위로 쪼개서 그 단위를 테스트하는 전통적인 프로그래
밍 테스팅 방법중의 하나
• 왜 필요한가?
• Regression testing 개념
– 인공적인 상황을 가정하고, 테스트모듈이 그 상황을 이용하여, 결과값을 계산한
다. 이때 기대되는 값과, 계산 값이 같은가를 확인한다.
– 프로그램이 퇴행하지 않도록 계속적으로 검사한다.
– 프로그램이 수정되는 것 뿐만 아니라, 플랫폼이나 주변 환경 등의 요소의 변화
에 의한 퇴행도 검사한다.
bioxp
100. Test Driven Development
• 테스트가 주도하는 프로그래밍
• 기본 사이클
– Write a test
– Make it compile, run it to see it fails
– Make it run
– Remove duplication
bioxp
101. TDD의 장점
• 테스트에는 실제 코드를 어떻게 사용하는지에 대해 작동하는 설명이 들어있다. (인
터페이스가 정의된다.)
• 따로 테스트를 할 필요가 없다.
• 코드 수정 시 기존의 테스트 코드를 통과하는지 체크되기 때문에 통합적인 테스트
가 유지된다.
• 테스트가 용이한 코드가 유지보수관리가 용이하다.
• 프로그램이 잘못되었는지를 "빨리" 알 수 있다(혹은 그럴 확률이 높다). (Fail early,
often)
• 어떤 기능을 구현할 때, 어떻게 사용할지를 먼저 생각하도록 이끄는 역할을 한다.
(Programming by intention)
• 오랜 시간이 지난 후에 다시 그 코드를 개선해야 할 일이 생길 때(혹은 어쨌던 봐야
할 일이 있을 때), 빨리 접근할 수 있도록 도와준다. (Documentation)
bioxp
108. Class statement
• Collection of variables and functions
• It is a kind of name space
class Person:
name = ‘yong’
gender = ‘male’
def get_age(self):
return 27
Person.name, Person.get_age()
113. Inheritance
• Is-a relationship. “Man is a person”
class Man(Person):
def __init__(self, name):
Person.__init__(self, name, „male‟)
class Woman(Person):
def __init__(self, name):
Person.__init__(self, name, „female‟)
yong = Man(„yong‟)
yong.gender, yong.set_age(27)
114. Multiple Inheritance
class Singer:
def song(self):
print “Oh my love~”
class ManSinger(Man, Singer):
def __init__(self, name):
Man.__init__(self, name)
yong = ManSinger(„yong‟)
yong.song()
115. Subclassing
class MyList(list):
def __sub__(self, other):
L = self[:]
for x in other:
if x in L:
L.remove(x)
return L
>>> L = MyList([1,2,3,‟spam‟,4,5])
>>> L = L – [„spam‟]
>>> print L
[1, 2, 3, 4, 5]
116. Polymorphism
class Animal:
def cry(self):
print „…‟
class Dog(Animal):
def cry(self):
print „멍멍‟
class Duck(Animal):
def cry(self):
print “꽥꽥”
for each in (Animal(), Dog(), Duck()):
each.cry()
117. Composition
• has-a relationship.
class Set(list):
def union(self, A):
result = self[:]
for x in A:
if x not in result:
result.append(x)
return Set(res)
A = MySet([1,2,3])
B = MySet([3,4,5])
print A.union(B)
118. Encapsulation
• Python do not support complete private
• “from module import *” do not import name “_” starting
class Encapsulation:
z = 10
__x = 1
>>> Encapsulation.z
>>> Encapsulation.__x
>>> Encapsulation._Encapsulation__x
120. Decorator
• 함수를 장식(decoration)하는 함수
def mydecorator(function):
@A @B @C def wrapper(*args, **kwargs):
def f(): ## do something for decoration
…. result = function(*args, **kwargs)
return result
def f(): …. return wrapper
f = A(B(C(f)))
def require_int(function):
def wrapper(arg):
assert isinstance(arg, int)
return function(arg)
return wrapper
@require_int
def p1(arg):
print arg
121. Decorator
• 인수를 가질 수도 있다.
def mydecorator(arg1, arg2):
def _mydecorator(function):
def __mydecorator(*args, **kwargs):
#do somethings for decoration
result = function(*args, **kwargs)
return result
return __mydecorator
return _mydecorator
@mydecorator(1, 2)
def f(arg):
….
122. Static method
• 인스턴스를 생성하지 않고 클래스 이름으로 직접 호출할 수 있
는 메쏘드
• Instance method는 이처럼 호출하면 unbounded method 오류
class D:
def spam(x, y): # self 가 없다.
print „static method‟, x, y
spam = staticmethod(spam)
D.spam(1, 2) class D:
@staticmethod
def spam(x, y):
print „static method‟, x, y
123. Class method
• 일반 메쏘드가 첫 인수(self)로 인스턴스 객체를 받는 것에 비해
서, 클래스 메쏘드는 첫 인수로 클래스 객체를 받는다.
class C:
def spam(cls, y): # self 가 없다.
print „class method‟, cls, y
spam = classmethod(spam)
>>> C.spam(5) class C:
__main__.C 5 @classmethod
def spam(cls, y):
print „class method‟, cls, y
124. get/set property
• 멤버 값을 정의할 때 편하게 사용하기 위함
• <예제> degree에 변수에 값을 저장하는데 360도 미만의 범위
에서 정규화 하기
class D(object):
def __init__(self):
self.__degree = 0
def get_degree(self):
return self.__degree
def set_degree(self, d):
self.__degree = d % 360
degree = property(get_degree, set_degree)
d = D()
d.degree = 10 # set_degree call
print d.degree # get_degree call
125. Iterator
• 순차적으로 참조는 하나, 인덱싱에 의한 순서적인 참조는 의미
가 없는 경우 메모리 효율
• iter() 내장함수로 만들며, next() 메쏘드를 갖는다.
• 더 이상 넘겨줄 자료가 없으면 StopIteration 예외
>>> I = iter([1,2,3])
>>> I
<iterator object at 0x1234556>
>>> I.next()
1
>>> I.next() >>> I.next() # 더이상 자료가 없으면 StopIteration
2 Traceback (most recent call last):
>>> I.next() File "<pyshell#71>", line 1, in ?
3 I.next()
StopIteration
126. Iterator on class
• iter(s) 에 의해 s.__iter__() 가 호출되고 반복자 객체를 리턴한
다.
• 반복자 객체는 next() 메쏘드를 갖는다.
class Seq:
def __init__(self, fname):
self.file = open(fname)
def __iter__(self):
return self
>>> s = Seq(„readme.txt‟)
def next(self):
>>> for line in S:
line = self.file.readline()
print line,
if not line:
raise StopIteration
return line
127. Generator
• icon 이란 언어에서 영향을 받음
• 기존의 함수 호출방식 – 인수들과 내부 변수들이 스택을 이용
생성 소멸
• 발생자란 (중단된 시점부터) 재실행 가능한 함수
• 어떤 함수이든 yield 를 가지면 발생자 함수
• 일종의 내맘대로 만드는 iterator
def generate_int(n):
while True: def generate_int(n):
yield n while True:
n += 1 return n
n += 1
128. Generator example
• 피보나치 수열
def fibonacci(a=1, b=1):
while 1:
yield a
a, b = b, a+b
t = fibonacci() # t는 반복자
for i in range(10):
print t.next(),
129. Generator example
• 홀수 집합 만들기 (iterator 이용)
class Odds:
def __init__(self, limit=None):
self.data = -1
self.limit = limit
def __iter__(self):
return self
def next(self):
self.data += 2
if self.limit and self.limit <= self.data:
raise StopIteration
return self.data
>>> for k in Odds(20):
print k,
1 3 5 7 9 11 13 15 17 19
130. Generator example
• 홀수 집합 만들기 (generator 이용)
def odds(limit=None):
k=1
while not limit or limit >= k:
yield k
k += 2
>>> for k in odds(20):
print k,
1 3 5 7 9 11 13 15 17 19
131. Generator expression
• List comprehension
>>> [k for k in range(100) if k % 5 == 0]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
• Generator expression
>>> (k for k in range(100) if k % 5 == 0) <generator object at 0x40190e4c>
• Other example
>>> sum(x for x in range(1, 20) if x % 2)
>>> “, “.join(x for x in [“abc”, “def”] if x.startswith(“a”))
132. Iterator / generator 가 사용되는 곳
• iter()
• xrange()
• dict.iteritems(), dict.iterkeys(), dict.itervalues()
• file은 라인단위의 반복자를 지원한다.
• reversed()는 iterator를 받지 않는다.
133. Itertools module
• http://docs.python.org/library/itertools.html
• Infinite iterator: count, cycle, repeat
• Finite iterator: chain, groupby, ifilter,…
• Combinatoric iterator: product, permutations, combinations
>>> text = “Hello world my world”
>>> wd = dict( (k, len(list(v))) for k, v in groupby( sorted(text.split() ), lambda x:
x.upper()) )
134. Excersize
임의의 FASTA 형식의 파일에 저장된 DNA 서열을 읽어
Reverse complement 서열을 출력하시오 (Multiple FASTA)
$ python reverse_complement.py < input.fasta
> seq1 reverse complement
AGTCAAGGCCAAGTCCAA
AGCAGCAGGAGCCAAGGT
> seq2 reverse complement
AGTCAAGGCCAAGTCCAA
AGCAGCAGGAGCCAAGGT
136. Library?
• 특정 기능을 수행하기 위한 모듈 및 패키지 import 하여 사용
• Python libraries
– Built-in library : 파이썬 설치시 같이 설치됨
• math, StringIO, random, unittest, re, itertools, decimal
• os, sys, subprocess, glob, pickle, csv, datetime, Tkinter, …
– 3rd party library : 따로 설치하여 사용해야함
• wxPython, PythonWin, numpy, scipy, matplotlib, Biopython, PIL,
BeautifulSoup…
137. os
• Miscellaneous operating system interfaces
• 운영체제 의존적인 기능들을 일관적으로 사용
• os.name ‘posix’, ‘nt’, ‘mac’, ‘os2’, ‘ce’, ‘java’, ‘riscos’
• os.environ 시스템 환경변수 사전
• os.chdir 현재 디렉토리 변경
• os.stat 파일의 속성
• os.walk 특정 디렉토리 하위 모든 파일들에 대한 일괄작업
• os.fork 프로세스 분기
138. sys
• System-specific parameters and functions
• 시스템운영에 관련된 특정 상수값들과 함수
• sys.argv 명령행 인수
• sys.getdefaultencoding() 기본 인코딩
• sys.stdin, sys.stdout 표준입출력
139. Subprocess
• Subprocess management
• 다른 프로그램 이용하기
– Shell pipeline
– Process spawn
• Popen, PIPE
140. glob
• Unix style pathname pattern expansion
• 와일드카드를 이용한 디렉토리내 파일 탐색
– ? : 아무런 문자 하나
– * : 0개 이상의 아무 문자
– [ ] : 사이에 나열된 문자 중 하나
– - : 일정 범위 a-z
142. csv
• CSV File Reading and Writing
• 표 데이터를 다루는 일반적인 방법
• CSV format : “,” 로 컬럼 구분. ‘ “” ’로 데이터 구분
• reader() and writer()
143. datetime
• Basic date and time types
• 날짜와 시각(시간)을 다루기
• date, time, datetime, timedelta, tzinfo
144. Tkinter
• Python interface to Tcl/Tk
• Built-in GUI library, 운영체제 독립
145. wxPython
• Advanced GUI library for python
• http://www.wxpython.org
• 3rd party GUI library, 운영체제 독립
• PythonWin 과 구분
146. numpy , scipy, matplotlib
• numpy : 행렬, 벡터방식의 수치해석
• scipy : 각종 과학연산용 라이브러리
• matplotlib : matLab 프로그램의 영향을 받은 차트 라이브러리