Python 2 ObjectOriented language Object instance A instance
Python 이란? 2. 객체지향 언어 (Object-Oriented language) : 객체(Object) 라는 개념을 사용하는 언어 기능 (함수) 변수나 값 instance A instance B instance C
자료형과 변수 선언 Python의 자료형 : number(int, long, float, complex), string, list, tuple, dictionary, set… int (signed) long float complex 10 51924361 L 0. 0 3. 14 j 100 -0 x 19323 L 15. 20 45. j -786 0122 L -21. 9 9. 322 e-36 j 080 0 x. DEFABCECBDAECBFBAEl 32. 3+e 18 . 876 j -0490 535633629843 L -90. -. 6545+0 J -0 x 260 -052318172735 L -32. 54 e 100 3 e+26 J -사칙연산, 괄호 자유롭게 사용가능 - ‘/’ 연산 (division) 의 경우는? http: //www. tutorialspoint. com/python_quick_guide. htm
자료형과 변수 선언 Python의 자료형 : number(int, long, float, complex), string, list, tuple, dictionary, set… num 0 = 1 num 1 = 100000 L num 2 = 80. 0 num 3 = 3. 14 j # 3. 0 이상부터는 L 선언 쓰이지 않음 # numbers str 0 = ‘Hello’ str 1 = “Hello World!” str 2 = “““Hello World! Hello Again!””” # string >>> str 0[0] ‘H’ >>> str 0[: -1] ‘Hell’ - 따옴표를 쓰려면 escape sequence (backslash ‘) 사용 - print function 을 사용하면 일반 모양으로 출력 - 스트링 인덱스 사용시 항상 시작 지점은 포함, 끝나는 지점은 미포함
자료형과 변수 선언 Python의 자료형 : number(int, long, float, complex), string, list, tuple, dictionary, set… li 0 = [ ] li 1 = [‘a’, ‘b’, ‘c’, ‘d’] li 2 = [num 0, num 1, num 2, num 3] # list tup 0 = ( ) tup 1 = (‘a’, ‘b’, ‘c’, ‘d’) tup 2 = (num 0, num 1, num 2, num 3) # tuple - tuple = immutable list https: //docs. python. org/3/library/stdtypes. html
자료형과 변수 선언 https: //docs. python. org/3/library/stdtypes. html Common sequence operation: : mutable 과 immutable sequence 모두에 적용되는 기능 Operation Result x in s True if an item of s is equal to x, else False x not in s False if an item of s is equal to x, else True s+t the concatenation of s and t s * n or n * s n shallow copies of s concatenated s[i] ith item of s, origin 0 s[i: j] slice of s from i to j s[i: j: k] slice of s from i to j with step k len(s) length of s min(s) smallest item of s max(s) largest item of s s. index(x[, i[, j]]) s. count(x) index of the first occurrence of x in s (at or after index i and before index j) total number of occurrences of x in s
자료형과 변수 선언 https: //docs. python. org/3/library/stdtypes. html Mutable sequence operation Operation Result s[i] = x item i of s is replaced by x s[i: j] = t slice of s from i to j is replaced by the contents of the iterable t del s[i: j] same as s[i: j] = [] s[i: j: k] = t the elements of s[i: j: k] are replaced by those of t del s[i: j: k] removes the elements of s[i: j: k] from the list s. append(x) appends x to the end of the sequence (same as s[len(s): len(s)] = [x]) s. clear() removes all items from s (same as del s[: ]) s. copy() creates a shallow copy of s (same as s[: ]) s. extend(t) extends s with the contents of t (same as s[len(s): len(s)] = t) s. insert(i, x) inserts x into s at the index given by i (same as s[i: i] = [x]) s. pop([i]) retrieves the item at i and also removes it from s s. remove(x) remove the first item from s where s[i] == x s. reverse() reverses the items of s in place
자료형과 변수 선언 사전 : key와 value의 쌍으로 구성된 자료형 dict 0 = {‘apple’: ‘fruit’, ‘carrot’: ‘vegetable’, ‘banana’: ‘fruit’} dict 1 = dict(apple=‘fruit’, carrot=‘vegetable’, banana=‘fruit’) dict 2 = dict(zip([‘apple’, ‘carrot’, ‘banana’], [‘fruit’, ‘vegetable’, ‘fruit’])) >>> dict 0[‘apple’] ‘fruit’ >>> dict 0. get(‘carrot’) ‘vegetable’ - dictionary = hash table - 순서는 입력한 순서대로 저장되지 않을 수도 있다. https: //docs. python. org/3/library/stdtypes. html
분기문 (조건문) : if, else if condition 1: # do something elif condition 2: # do something else: # do something 분기문, 조건문 등의 범위는 콜론 다음 줄을 들여써서 지정한다. condition 자리에는 True/False 로 판단할 수 있는 표현을 쓴다. https: //docs. python. org/3/reference/index. html
반복문 : while, for while condition: # do something for item in sequence: # do something (with item) words = [‘cat’, ‘elephant’, ‘snake’] >>> for animal in words: print(animal, len(animal)) sequence: list, tuple, string, iterator, view… for num in range(10): print(num) if num == 7: break for key in dict 1. keys(): if key == ‘apple’: continue print(key) - break, continue 로 반복문 추가조절 가능
반복문 : while, for while condition: # do something for item in sequence: # do something (with item) words = [‘cat’, ‘elephant’, ‘snake’] >>> for animal in words: print(animal, len(animal)) sequence: list, tuple, string, iterator, view… Task 1) 1~100 의 정수 중 5의 배수는 화면에 출력하고, 3의 배수의 합을 구해 마지막에 출력 해 보세요. (나머지는 % 연산자) Task 2) ‘Hello. World’ 라는 문자열의 각 문자 에 대해 아스키 코드값을 구하고, ‘H: 72’ 처럼 각각 출력해 보세요. (코드값은 ord(char) 로 구한다)
함수 정의 : def funcname(param): # do something (with param) # and maybe return something def addition 1(num 1, num 2): return num 1+num 2 def addition 2(num 1, num 2): print(num 1+num 2) Task 1) 정수 n을 인자로 받아서 n번째 피보나 치 숫자를 리턴하는 함수 fibo(n) 을 정의해 보 세요. Task 2) 정수 n을 인자로 받아서 n번째까지의 모든 피보나치 숫자를 리스트에 담아 리턴하는 함수 fibo 2(n) 을 정의해 보세요. (리스트 x에 y 를 추가하려면 x. append(y)) >>> print(addition 1(3, 5)) 8 >>> addition 2(3, 5)) 8 https: //docs. python. org/3/tutorial/controlflow. html
입출력 커맨드라인 입출력 : input([ prompt]), print >>> str 0 = input(“Command line input: “) Command line input: Hello World >>> print(str 0) ‘Hello World’ https: //docs. python. org/3/tutorial/inputoutput. html
입출력 파일 입출력 : open(filename, mode), read(), write(string) with open(‘test. txt’, ‘r’) as myfile: text = myfile. read() # reads whole file oneline = myfile. readline() # reads one line with open (‘test 2. txt’, ‘w’) as myfile 2: myfile 2. write(‘helloworldn’) 쓰기모드 ‘w’ 읽기모드 ‘r’ 읽기쓰기모드 ‘r+’ 어펜딩모드 ‘a’ 바이너리모드 ‘b’ (지정하지 않으면 ‘r’) 파일 객체는 반복문의 sequence 부분에 사용할 수 있다. https: //docs. python. org/3/tutorial/inputoutput. html
모듈 모듈 : . py로 저장된 파일 (함수, 정의 등을 포함하고 있음, 상위단위 = package) import modname. func(param) local = modname. func local(param) from modname import func 1, func 2 func 1(param) from modname import *
모듈 기본 제공 모듈 (Standard modules) : 파이썬에서 자체 제공하는 모듈들 텍스트 처리: string, re, unicodedata… 바이너리 처리: struct, codecs… 데이터타입: datetime, calendar, collections… 숫자: numbers, math, random… os: os, io, argparse, optparse… 인터넷 프로토콜: webbrowser, http, urllib… import modulename from modulename import * https: //docs. python. org/3/library/index. html
모듈 기본 제공 모듈 (Standard modules) : 파이썬에서 자체 제공하는 모듈들 from urllib. request import urlopen url = “http: //www. gutenberg. org/cache/epub/78/pg 78. txt” text = urlopen(url). readlines() Task 1) “The”로 시작하는 줄만 출력해 보세요. (They, Then 등이 나오지 않게 주의) Task 2) “The”로 시작하는 줄, “the”로 시작하는 줄을 모두 출력해 보세요. Task 3) 사용자 인풋을 받아서 그 인풋으로 시작하는 줄을 출력하는 코드를 만들어 보세요. code from Natural Language Processing with Python, by Steven Bird, Ewan Klein and Edward Loper (2009)
예외처리 예외 : 문법적으로 오류가 없더라도 실행 중 에러를 일으키는 경우 >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in ? Zero. Division. Error : division by zero try: # do something except Error. Name: # do something except: # do something (e. g. raise) else: # do something that must be done (e. g. closing file) https: //docs. python. org/3/tutorial/errors. html
클래스 : 객체의 정의 class Class. Name: member = 12345 def func(self): return ‘Hello World!’ class Class. With. Init: def __init__(self, x, y): self. x = x self. y = y new = Class. Name() new. func() new 2 = Class. With. Init(1, 2) new. x new. y https: //docs. python. org/3/tutorial/classes. html http: //neopythonic. blogspot. kr/2008/10/why-explicit-self-has-to-stay. html
클래스 상속 (inheritance) : 부모 클래스의 메소드, 멤버 등을 자식 클래스가 이어받는 것 class Base. Class: member = 12345 def func(self): return ‘Hello World!’ class Derived. Class(Base. Class): newmember = 23456 x = Derived. Class() x. member x. func() x. newmember https: //docs. python. org/3/tutorial/classes. html http: //neopythonic. blogspot. kr/2008/10/why-explicit-self-has-to-stay. html
코딩스타일 (coding style, coding convention) : 코드의 가독성, 공유, 유지보수, 수정 등을 용이하게 하기 위해 따르는 코딩 방식 import sys, os, re, urllib, glob, math, random (X) import sys import os import re … (O) http: //legacy. python. org/dev/peps/pep-0008/
코딩스타일 (coding style, coding convention) : 코드의 가독성, 공유, 유지보수, 수정 등을 용이하게 하기 위해 따르는 코딩 방식 class my_class: def __init__(self, a, B): self. x = a self. y = B def MYFunction(self, c): print (“{0}, {1}, {2}”. format(self. x, self. y, self. c)) => ? ? http: //legacy. python. org/dev/peps/pep-0008/
코딩스타일 (coding style, coding convention) : 코드의 가독성, 공유, 유지보수, 수정 등을 용이하게 하기 위해 따르는 코딩 방식 class student: def __init__(self, student_number, student_name): self. student_number = student_number self. student_name = student_name def print_student_info(self, comment): print (“{0}, {1}, {2}”. format(self. student_number, self. student_ID, comment)) http: //legacy. python. org/dev/peps/pep-0008/
코딩스타일 (coding style, coding convention) : 코드의 가독성, 공유, 유지보수, 수정 등을 용이하게 하기 위해 따르는 코딩 방식 if foo == “bar”: do_something() do one(); do_two(); do_three(arg 0, arg 1, arg 2, arg 3) if foo == “bar”: do_something() do_one() do_two() do_three(arg 0, arg 1, arg 2, arg 3) http: //legacy. python. org/dev/peps/pep-0008/
코딩스타일 일반적으로 많이 쓰이는 이름짓기 방식 패키지/모듈명 : short, all-lowercase e. g. re. sub 클래스/예외명 : Cap. Words 방식 e. g. My. Class 함수/전역변수 : lowercase with underscore e. g. do_something, my_var 상수 : all-capital with underscore e. g. MAX_SIZE http: //legacy. python. org/dev/peps/pep-0008/
Documentation : https: //docs. python. org/3/index. html
Py. PI : https: //pypi. python. org/pypi 내장모듈 이외에 추가적인 모듈이나 패키지를 찾고 싶을 때 사용 > 보통은 pip install packagename 으로 설치 가능하다. (pip을 설치해야 한다면 https: //pip. pypa. io/en/latest/installing. html ) pip install packagename==1. 0. 4 (버전명 명시 가능) pip install --upgrade packagename (업그레이드)
re 모듈과 정규표현식 re (https: //docs. python. org/3/library/re. html ) : 정규표현(regular expression, regex) 을 통한 패턴매칭 지원 re. search( pattern, string, flags=0) : string 에 pattern 이 존재하면 match 객체를 리턴하고, 없으면 None을 리턴한다. re. split( pattern, string, maxsplit=0, flags=0) : pattern 으로 string을 나누어서 나뉜 부분들의 리스트를 리턴한다. re. findall( pattern, string, flags=0) : string 에서 겹치는 부분이 없는 모든 pattern 을 찾아 리스트를 만들어 리턴한다. re. sub( pattern, repl, string, count=0, flags=0) : string 에서 pattern 을 찾아 repl로 바꾼다.
pdb (debugger) 모듈 pdb(https: //docs. python. org/3/library/pdb. html ) : 인터랙티브 파이썬 디버깅 모듈 import pdb. run(“code to run”) break, step, next, up, down, return, continue, jump lineno, args 가능 import pdb # some code pdb. set_trace() # some code > 코드실행시 set_trace() 한 지점에 breakpoint 생김 등의 디버거 커맨드 사용
효율적인 코딩 문제: 다음 두 코드는 같은 기능을 수행합니다. 차이점은 무엇일까요? (Python 2. 7 기준) (1) for word in text: my_dict[word] = (my_dict[word] + 1) if word in my_dict. keys() else 1 (2) for word in text: my_dict[word] = my_dict. get(word, 0)+1
효율적인 코딩 문제: 다음 두 코드는 같은 기능을 수행합니다. 차이점은 무엇일까요? (Python 2. 7 기준) (1) for word in text: my_dict[word] = (my_dict[word] + 1) if word in my_dict. keys() else 1 my_dict. keys( ) 는 키 리스트를 반환 (3. 0 이상에서는 view object) > 리스트 타입에서 in 구문을 이용한 membership 확인 (2) for word in text: my_dict[word] = my_dict. get(word, 0)+1 > 파이썬 사전(=hash table) 타입의 get 메소드는 hash search
- Slides: 51