welcome to python
TRANSCRIPT
Welcome to Python2015 Summer Data Mining Workshop
August 20, 2015
Kyunghoon [email protected]
Department of Mathematical SciencesUlsan National Institute of Science and Technology
Republic of Korea
1Contents
Python왜프로그래밍을배워야하나?왜파이썬을사용하나?어떻게파이썬을배우나?파이썬2냐파이썬3냐
파이썬배우기
파이썬코드와실행
객체 Objecthelp(), dir()변수의자료형주석 comment리스트 list사전 dictionary
함수 Function반복문 Loop statement조건문 Conditional statement클래스 Class
2왜프로그래밍을배워야하나?
https://www.youtube.com/watch?v=nKIu9yen5nc
3왜파이썬을사용하나?
http://www.collegeteacher.org/csci101/resource_programming/prog03.php
4왜파이썬을사용하나?
5왜파이썬을사용하나?
http://www.quora.com/Why-should-I-learn-Python-if-I-already-know-Java
6왜파이썬을사용하나?
http://www.quora.com/Why-should-I-learn-Python-if-I-already-know-Java
8왜파이썬을사용하나?
Python is a programming language that lets you work quickly andintegrate systems more effectively.
https://www.python.org/
9어떻게파이썬을배우나?
▶ English : http://code.tutsplus.com/articles/the-best-way-to-learn-python--net-26288
▶ Korean : https://nolboo.github.io/blog/2014/08/10/the-best-way-to-learn-python/
10어떻게파이썬을배우나?
Web Tutorial(links)▶ Codecademy python-ko▶ Python Visualization▶ ipython Tutorial▶ Learn Python Online
11어떻게파이썬을배우나?
Slide(links)▶ Learn 90% of Python in 90 Minutes▶ 산업공학과를위한프로그래밍입문
12어떻게파이썬을배우나?
Online Book(links)▶ 점프투파이썬
▶ Dive into Python(번역본)▶ 컴퓨터과학자같이생각하는법(파이썬버전)▶ Problem Solving with Algorithms and Data Structures▶ 파이썬문서고
13어떻게파이썬을배우나?
15파이썬2냐파이썬3냐
http://www.slideshare.net/pablito56/python-2-vs-python-3
16파이썬코드와실행
hello.py1 print("hello world")
Command prompt1 $ python hello.py
17객체 Object
Everything in Python is an object▶ identity(id)▶ value
▶ mutable▶ list▶ dictionary
▶ immutable▶ string▶ integer▶ tuple
18help(), dir()
정의된객체에관한문서를얻을때사용하는명령어.
1. help()객체에대해뭔가알고싶다
1 >>> help(dir)2 Help on built-in function dir in module __builtin__:3
4 dir(...)5 dir([object]) -> list of strings
2. dir()객체의속성에관한목록을얻고싶다
1 >>> dir(help)2 [‘__call__’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ...]
19변수의자료형
변수는자료형이없어서선언할필요가없다.1 >>> a = 3 # integer2 >>> b = 3.14 # float3 >>> c = "string" # string4 >>> d = ‘string’5 >>> e = "3"
1 >>> type(a)2 int3 >>> type(b)4 float5 >>> type(c)6 str
20정수의자료형
고정소수점 Fixed point방식
int : 마이크로프로세서의기본비트의길이1 >>> import sys2 >>> print(sys.maxint)3 9223372036854775807
long : 정수의범위를넘어서는큰숫자(only python2)1 >>> print(sys.maxint+1)2 9223372036854775808L
21실수의자료형
부동소수점 Floating point방식: 소수점의위치를고정하지않고그위치를나타내는수(exponent)를따로적음
[mantissa] ∗ [base][exponent]
정밀도 precision문제발생
1 >>> (1234.567+0.001)+0.00042 1234.5683999999999
1 >>> 1234.567+(0.001+0.0004)2 1234.5684
22정밀도설정
decimal객체를생성하여 10진수를정확하게나타낼수있음.
1 >>> from decimal import Decimal, getcontext # Module import2 >>> getcontext().prec = 12 # precision3 >>> Decimal(1234.567)+Decimal(0.001)+Decimal(0.0004)4 Decimal(‘1234.56840000’)5 >>> getcontext().prec = 246 >>> (Decimal(1234.567)+Decimal(0.001))+Decimal(0.0004)7 Decimal(‘1234.56840000000000727600’)8 >>> Decimal(1234.567)+(Decimal(0.001)+Decimal(0.0004))9 Decimal(‘1234.56840000000000727600’)
10 >>> Decimal(10)**60011 Decimal(’1.00000000000000000000000E+600’)
하지만.. 긴시간의연산에서는느리다.
23정수의나눗셈
1 >>> 3/42 03 >>> 3/4.4 0.75
Python3에서는문제가없다.
24복소수
실수,허수부분은 64비트부동소수점숫자로저장됨.1 >>> a = 1-2j2 >>> a.real3 1.04 >>> a.imag5 -2.06 >>> abs(a)7 2.236067977499798 >>> a9 (1-2j)
25문자열
1 >>> a = ‘apple’2 >>> b = "apple"3 >>> c = """apple"""4 >>> print a, b, c5 apple apple apple
String Escaping1 >>> print "I’m happy"2 I’m happy3 >>> print ‘I\’m happy’4 I’m happy5 >>> print """\"I’m happy\""""6 "I’m happy"
26문자열포맷
1 >>> a = "apple"2 >>> b = "banana"3 >>> "%s and %s" % (a, b)4 ‘apple and banana’5 >>> "0 and 1".format(a, b)6 ‘apple and banana’7 >>> print a, "and", b8 apple and banana
27문자열방법
Dunder(Double under) Methods and String Methods1 >>> dir("apple")2 [’__add__’, ’__class__’, ’__contains__’, ’__delattr__’,3 ’__doc__’, ’__eq__’, ’__format__’, ’__ge__’, ’__getattribute__’,4 ...5 ’capitalize’, ’center’, ’count’, ’decode’, ’encode’,6 ’endswith’, ’expandtabs’, ’find’, ’format’, ’index’,7 ’isalnum’, ’isalpha’, ’isdigit’, ’islower’, ’isspace’,8 ’istitle’, ’isupper’, ’join’, ’ljust’, ’lower’, ’lstrip’,9 ’partition’, ’replace’, ’rfind’, ’rindex’, ’rjust’,
10 ’rpartition’, ’rsplit’, ’rstrip’, ’split’, ’splitlines’,11 ’startswith’, ’strip’, ’swapcase’, ’title’, ’translate’,12 ’upper’, ’zfill’]
28주석 comment
1 # 한 줄 주석2
3 """4 여러 줄 주석5 """
29그외자료형들
▶ None▶ Booleans▶ Sequences
▶ list▶ tuple▶ set
▶ Dictionary
30리스트 list
1 >>> a = [’apple’, ’banana’, ’kiwi’]2 >>> a[0]3 ’apple’4 >>> a[2]5 ’kiwi’6 >>> a[-1] # a[len(a)-1]7 ’kiwi’8 >>> len(a)9 3
31리스트 list
1 >>> dir([])2 [..., ’append’, ’count’, ’extend’, ’index’,3 ’insert’, ’pop’, ’remove’, ’reverse’, ’sort’]4
5 >>> a.append(’melon’)6 >>> a7 [’apple’, ’banana’, ’kiwi’, ’melon’]8 >>> a.index(’kiwi’)9 2
10 >>> a.remove(’banana’)11 >>> a12 [’apple’, ’kiwi’, ’melon’]13 >>> a.pop(2)14 ’melon’15 >>> a16 [’apple’, ’kiwi’]
32리스트 list
1 >>> range(10) # half-open interval2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]3 >>> range(3, 10) # length = end - start4 [3, 4, 5, 6, 7, 8, 9]5 >>> range(1, 10, 2)6 [1, 3, 5, 7, 9]7 >>> a = range(10)8 >>> a9 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
10 >>> a[3:5]11 [3, 4]12 >>> a[::-1]13 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
33사전 dictionary
Hashmap, Associative array1 >>> a = {} # a = dict()2 >>> a[’apple’] = 5003 >>> a[’banana’] = 2004 >>> a5 {’apple’: 500, ’banana’: 200}
1 >>> dir({})2 [...,’clear’, ’copy’, ’fromkeys’, ’get’, ’has_key’, ’items’,3 ’iteritems’, ’iterkeys’, ’itervalues’, ’keys’, ’pop’,4 ’popitem’, ’setdefault’, ’update’, ’values’, ’viewitems’,5 ’viewkeys’, ’viewvalues’]
34사전 dictionary
1 >>> apple = dict()2 >>> apple = {"price": 500, "type": ["fruit", "red"],3 "property": {"a": 1}}4 >>> apple[’price’]5 5006 >>> apple[’type’]7 [’fruit’, ’red’]8 >>> apple[’type’][0]9 ’fruit’
10 >>> apple[’property’]11 {’a’: 1}12 >>> apple[’property’][’a’]13 114 >>> apple.get("price", None)15 50016 >>> apple.get("where", None)17 >>>
35그외유용한자료형들
1 >>> values = [1,1,1,2,3,3,4,5,6,7,7]2 >>> set(values) # 집합 set3 set([1, 2, 3, 4, 5, 6, 7])4 >>> list(set(values))5 [1, 2, 3, 4, 5, 6, 7]
1 >>> a = (11, 23, "Monday") # 튜플 tuple2 >>> (mon, day, text) = a3 >>> print mon, day, text4 11 23 Monday
36함수 Function
f (x) = 4x ∗ (1 − x)
1 >>> def f(x):2 return 4*x*(1-x)3 >>> f(0.2)4 0.6400000000000001
37함수 Function
1 >>> from decimal import Decimal, getcontext2 >>> getcontext().prec = 243 >>> def f(a, x):4 """ Logistic Function """5 x = Decimal(x)6 return a*x*(1-x)7 >>> f(4, 0.2)8 Decimal(’0.640000000000000026645353’)9
10 >>> help(f)11 Help on function f in module __main__:12
13 f(a, x)14 Logistic Function
38반복문 Loop
1 >>> for i in [’apple’, ’banana’, ’kiwi’]:2 ... print i3 ...4 apple5 banana6 kiwi7
8 >>> for i in range(0, 10, 2):9 ... print i
10 ...11 012 213 414 615 8
39반복문 Loop
1 >>> x = 0.12 >>> for i in range(10):3 print x4 x = f(4, x) # logistic function5 print x6 0.17 0.3600000000000000177635688 0.9216000000000000198951959 0.289013759999999932897486
10 0.82193922612264948673834011 0.58542053873419824930112112 0.97081332624943734621213113 0.11333924730376348296114914 0.40197384929751930007619515 0.96156349511381817032339616 0.147836559913265400036406
40조건문 Conditional statement
1 >>> x = 0.12 >>> for i in range(100):3 print x4 x = f(2, x)5 print x6 0.17 0.1800000000000000088817848 0.2952000000000000113686849 0.416113920000000009313226
10 0.48592625116446720312500011 0.49960385918742867848795412 0.49999968614491323066624113 0.49999999999980298996901814 0.50000000000000000000000015 0.50000000000000000000000016 0.50000000000000000000000017 0.500000000000000000000000
41조건문 Conditional statement
1 >>> x = Decimal(0.1)2 >>> for i in range(100):3 print x4 new_x = f(2, x)5 if new_x - x < 0.0000001:6 print "Converged"7 break8 else:9 x = new_x
10 print x11 0.100000000000000005551115123125782702118158340454101562512 0.18000000000000000888178413 0.29520000000000001136868414 0.41611392000000000931322615 0.48592625116446720312500016 0.49960385918742867848795417 0.49999968614491323066624118 0.499999999999802989969018 Converged
42조건문 Conditional statement
1 >>> A = 852 >>> if A>90:3 ... print "A"4 ... elif A>80:5 ... print "B"6 ... elif A>70:7 ... print "C"8 ... else:9 ... print "D"
10 ...11 B
43반복문과조건문예
1 >>> animals = [’cat’, ’dog’, ’cock’, ’rabbit’]2 >>> for index, value in enumerate(animals):3 ... print index, value4 ...5 0 cat6 1 dog7 2 cock8 3 rabbit9
10 >>> for index, value in enumerate(animals):11 ... if value[0] == ’c’:12 ... print index, value13 ...14 0 cat15 2 cock
44클래스 Class
▶ object▶ constructor(dunder init)▶ All method take self as first parameter.
1 >>> class Animal(object):2 ... def __init__(self, name):3 ... self.name = name4 ... def talk(self):5 ... print "Hello"6 ...7 >>> animal = Animal(’thing’)8 >>> animal.talk()9 Hello
45서브클래스 Subclass
1 >>> class Cat(Animal):2 ... def talk(self):3 ... print "%s is cat name." % (self.name)4 ...5 >>> cat = Cat("Persia")6 >>> cat.talk()7 Persia is cat name.
Thank you for attention!In case you have any comments, suggestions or have found a
bug, please do not hesitate to contact me.
Kyunghoon [email protected]
Graduate Student inComputational Mathematical Sciences Laboratory
http://amath.unist.ac.kr