[[TableOfContents]] == 개요 == * [https://docs.python.org/3/tutorial]ì˜ ë‚´ìš©ì„ [열파참/금요ì¼]ì—ì„œ ì •ë¦¬. * 번ì—ì´ ì•„ë‹Œ ì •ë¦¬ë‹¤ë³´ë‹ˆ, ë‚´ìš©ì˜ ì°¨ì´ê°€ ìžˆì„ ìˆ˜ 있ìŒ... ì´ ì•„ë‹ˆë¼ ìžˆìŒ. * 스터디시만 사용하는 ë…스: http://goo.gl/11ZcFB == ë‚´ìš© == === Whetting Your Appetite === === Using the Python Interpreter === === An Informal Introduction to Python === ==== Using Python as a Calculator ==== ===== Numbers ===== * pythonì€ ê³„ì‚°ê¸°ì²˜ëŸ¼ 쓸 수 있ìŒ. * +, -, *, /, (), **, //, %ê°€ 존재. * //ì—°ì‚°ìžëŠ” ëª«ì„ ë¦¬í„´. * {{{x ** y}}} ì—°ì‚°ìžëŠ” xì˜ y승 == {{{pow(x, y}}}. * -x = x negated * int / int = floatì´ë‹ˆ 조심. * {{{_}}}: ë§ˆì§€ë§‰ì— ì¶œë ¥ëœ ê°’ì„ ì˜ë¯¸. * ë³µì†Œìˆ˜ë„ ë‚´ìž¥ìœ¼ë¡œ 지ì›í•¨: {{{complex(real, imaginary)}}} * {{{divmod(x, y)}}} => {{{(x // y, x % y)}}} ì´ëŸ° 형태로 ì¶œë ¥ë‹¹í•¨ * {{{round(x, y)}}}: 숫ìžxì—ì„œ 소수ì ìžë¦¬ìˆ˜ë¥¼ y개수만 남김. ===== Strings ===== * Stringì€ â€˜...’ í˜¹ì€ â€œ...â€ì‚¬ìš©. ì°¨ì´ëŠ” ì—†ìŒ. * 다른 언어와 ê°™ì´{{{\}}}를 ì´ìš©í•´ 특수 문ìžë¥¼ ìž…ë ¥ 가능. * {{{\t}}}, {{{\n}}}, {{{\’}}} 등. * ì¤‘ê°„ì— ìžˆëŠ”â€™ë¥¼ 무효화 시키기 위해서 \를 붙ì´ê±°ë‚˜ í°ë”°ì˜´í‘œë¥¼ 사용 * 단지 “...â€ ì•ˆì˜ â€˜ 는 허용. ‘...’ ì•ˆì˜ â€œ 허용. escape ë¬¸ìž í•„ìš”ì—†ìŒ * ’râ€™ì„ ë¶™ì´ë©´ {{{\}}}를 특수문ìžê°€ ì•„ë‹Œ ì¼ë°˜ 문ìžë¡œ 표현. {{{ >>> print('C:\some\name') # \nì„ ê°œí–‰ë¬¸ìžë¡œ ì¸ì‹ C:\some ame >>> print(r'C:\some\name') # rì„ ì•žì— ë¶™ì¸ë‹¤ C:\some\name }}} * Stringì„ {{{+}}}ë¡œ ë”í•˜ê³ , {{{*}}}ë¡œ ë°˜ë³µí• ìˆ˜ 있다. * {{{“““....â€â€â€}}} 여러 ì¤„ì„ í—ˆìš©í•˜ëŠ” 문ìžì—´ * {{{“some†“thingâ€}}} == {{{“somethingâ€}}} * ì˜¤ì§ literals ë¼ë¦¬ ì ìš©ëœë‹¤. * 변수, 수ì‹ì—ì„œ ì ìš©ë˜ì§€ ì•ŠìŒ * 긴 stringì„ ì—¬ëŸ¬ ì¤„ì— ê±¸ì³ì„œ 쓸 ë•Œ 사용하면 ìœ ìš© {{{ >>> prefix = 'Py' >>> prefix 'thon' SyntaxError: invalid syntax >>> ('un' * 3) 'ium' SyntaxError: invalid syntax }}} * index를 ì´ìš©í•´ì„œ ê° chrì— ì ‘ê·¼ 가능하며, ìŒìˆ˜ë„ 가능. {{{ +---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1 }}} * slicing: {{{[start:end:step]}}}. start는 í¬í•¨ë˜ë©°, end는 í¬í•¨ë˜ì§€ ì•Šê³ , ê° í•ëª©ì€ ìƒëžµ 가능. {{{ word = 'Python' >>> word[0:2] 'Py' >>> word[:2] + word[2:] 'Python' >>> word[:2] 'Py' >>> word[-2:] 'on' >>> word[:] ‘Python’ }}} * {{{len(s)}}}: stringê³¼ 기타 ë“±ë“±ì˜ ì›ì†Œì˜ 개수를 반환 ===== Lists ===== * Pythonì´ ê°€ì§€ëŠ” 여러가지 ìžë£Œë¥¼ 묶는 ë°©ì‹ ì¤‘ 가장 가변ì ì¸ í˜•íƒœ * []ë¡œ 묶어서 표현. {{{ >>> squares = [1, 4, 9, 16, 25] >>> squares [1, 4, 9, 16, 25] }}} * {{{[n]}}}으로 index nì— í•´ë‹¹í•˜ëŠ” ë°ì´í„°ì— ì ‘ê·¼ * + ë¡œ ë³µìˆ˜ì˜ list를 appendí• ìˆ˜ 있다. * {{{len()}}}: list와 기타 ë“±ë“±ì˜ ì›ì†Œì˜ 개수를 반환. * Slicing * Stringì´ëž‘ ë™ì¼í•˜ê²Œ ì ìš©. {{{>>> a = ['a', 'b', 'c'] >>> n = [1, 2, 3] >>> x = [a, n] >>> x [['a', 'b', 'c'], [1, 2, 3]] >>> x[0] ['a', 'b', 'c'] >>> x[0][1] 'b' }}} ==== First Steps Towards Programming ==== * {{{a, b = b, a+b}}} : ìš°ë³€ì„ ì—°ì‚°í•˜ê³ ì¢Œë³€ì˜ ëŒ€ì‘하는 ìœ„ì¹˜ì— ë§žì¶”ì–´ì„œ 대입한다. * Indentation 잘못하면 안 ë¼ìš”. === More Control Flow Tools === === Data Structures === === Modules === === Input and Output === ==== Fancier Output Formatting ==== * {{{str()}}} vs {{{repr()}}} * {{{str()}}}: ì‚¬ëžŒì´ ì½ê¸° 위한 ìš©ë„ë¡œ string으로 변환 * {{{repr()}}}: {{{eval()}}}ì„ ì‚¬ìš©í•˜ê¸° 위한 ìš©ë„ë¡œ string으로 변환 {{{ >>> s = 'Hello, world.' >>> str(s) 'Hello, world.' >>> repr(s) "'Hello, world.'" }}} * {{{str.format()}}} method를 ì´ìš©í•˜ë©´ 노가다를 뛰지 ì•Šê³ ë„ ê¹”ë”하게 ì¶œë ¥ì´ ê°€ëŠ¥ {{{ >>> for x in range(1, 3): ... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) ... 1 1 1 2 4 8 3 9 27 }}} {{{ >>> print('The story of {1}, {0}, and {other}.'.format('Manfred','Bill', other='Georg')) The story of Bill, Manfred, and Georg. }}} {{{ >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} >>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ' ... 'Dcab: {0[Dcab]:d}'.format(table)) Jack: 4098; Sjoerd: 4127; Dcab: 8637678 }}} {{{ >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} >>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) Jack: 4098; Sjoerd: 4127; Dcab: 8637678 }}} * {{{vars()}}}를 ì´ìš©í•˜ë©´ local variables를 ë‹´ì€ dictionary를 ì–»ì„ ìˆ˜ 있ìŒ. ìœ„ì˜ ì˜ˆì œì™€ ì“°ë©´ ê¶í•©ì´ 좋ìŒ. * {{{str.rjust(n)}}}, {{{str.ljust(n)}}}, {{{str.center(n)}}}: n사ì´ì¦ˆì— 맞게 ì •ë ¬ëœ stringì„ ë°˜í™˜. strì´ ì´ë¯¸ n보다 길면 무시. * ì´ì™€ ê°™ì€ ë¬¸ì œë¥¼ 해결하기 위해 {{{str.ljust(n)[:n]}}} ê°™ì€ ì§“ì„ ê°€ëŠ¥. * {{{str.zfill(n)}}}: n사ì´ì¦ˆì— 맞게 0ì´ ì‚½ìž…ëœ stringì„ ë°˜í™˜. ===== Old string formatting ===== * {{{%typeIndicator}}} * 구ì‹ì´ë‹¤. {{{ print(‘The value of PI is %5.3f.’ % math.pi) }}} ==== Reading and Writing Files ==== * {{{open(filename, mode)}}}: íŒŒì¼ ì—´ê¸° * mode * ‘r’: ì½ê¸° (기본값) * ‘w’: 쓰기 * ‘a’: ì´ì–´ì“°ê¸° * ‘r+’,’w+’: ì“°ê³ ì½ê¸° * ‘b’: ë°”ì´ë„ˆë¦¬ë¡œ 열기 (없으면 í…스트로 ì½ìŒ) * binary vs text * text modeì—서는 line endingì„ í”Œëž«í¼ì— 맞는 형ì‹ìœ¼ë¡œ 변환. * ë”°ë¼ì„œ textê°€ ì•„ë‹Œ 파ì¼ì„ text 모드로 ì—´ë©´ 파ì¼ì´ 변형ë 수 있ìŒ. ===== Methods of File Objects ===== * {{{read(size)}}} * sizeë§Œí¼ íŒŒì¼ì„ ì½ëŠ”다. sizeê°€ ì§€ì •ë˜ì§€ 않거나 ìŒìˆ˜ë©´ 메모리가 허용하는 ë§Œí¼ ì½ìŒ. * ëì— ë„달하면 빈 stringì¸ â€˜â€™ë¥¼ 반환 * {{{readline()}}} / {{{readlines()}}} * í•œ 줄 ì½ì–´ì˜¤ëŠ” 메소드/한줄씩 묶어서 리스트로 ì œê³µí•˜ëŠ” 메소드 * list(file)ë¡œë„ readlines와 ê°™ì€ íš¨ê³¼ * 다ìŒê³¼ ê°™ì´ forë¬¸ì„ ì´ìš©í• ìˆ˜ë„ ìžˆìŒ: {{{ for line in f: print(line, end=’’) }}} * {{{write(string)}}} * 파ì¼ì— stringì„ ì”니다. string만 가능하니 다른 ê²ƒì„ ì“°ê³ ì‹¶ë‹¤ë©´ str(object)ë¡œ 변환 후 ì´ìš©. * {{{seek(index,from)}}} : * from * 0 : 파ì¼ì˜ 시작ì ì„ ê¸°ì¤€ìœ¼ë¡œ * 1 : 현재 ë³´ê³ ìžˆëŠ” ë°”ì´íŠ¸ë¥¼ 기준으로(tell()ë¡œ ë³´ì´ëŠ” 그거) * 2 : 파ì¼ì˜ 마지막 ë°”ì´íŠ¸ë¥¼ 기준으로 * {{{tell()}}} * íŒŒì¼ ë‚´ì˜ í˜„ìž¬ ì§€ì •í•˜ê³ ìžˆëŠ” ë°”ì´íŠ¸ 위치를 ì•Œë ¤ì¤Œ * {{{close()}}} * 파ì¼ì„ ë‹«ìŒ. ë‹«ê³ ë‚˜ì„œ 해당 파ì¼ì„ ì“°ë ¤ê³ í•˜ë©´ 오류가 남. * {{{closed}}} * NOT A METHOD * 닫혔는지 여부를 boolean으로 ì•Œë ¤ì¤Œ ===== Saving structured data with json ===== * json = [http://json.org JavaScript Object Notation] * {{{import json}}} * {{{json.load(json file)}}} ë„ íŒŒì¼ ì½ê¸° 시스템. ì½ê³ ë‚œ ë’¤ì—는 마지막으로 간다. ê³ ë¡œ 여러번 ì½ì„ 수 없다. * {{{json.dumps(obj)}}}: obj를 json 형ì‹ìœ¼ë¡œ ì „í™˜ * {{{json.dump(obj, file)}}} : fileì— ì“°ê¸° === Errors and Exceptions === ==== Syntax Errors ==== * {{{SyntaxError}}} - 문법 오류. íŒŒì‹±ì„ í•˜ë‹¤ ë¬¸ì œê°€ ìƒê¸°ë©´ ë°œìƒ * ìžì£¼ 틀리는 문법 오류 * 들여쓰기 * 따옴표 * {{{:}}} ==== Exceptions ==== * 문법ì 으로는 맞지만 ì‹¤í–‰í•˜ë ¤ê³ ì‹œë„하는 ì¤‘ì— ë°œìƒí•˜ëŠ” ì—러. * {{{ZeroDivisionError}}}, {{{NameError}}}, {{{TypeError}}}, [https://docs.python.org/3.4/library/exceptions.html#bltin-exceptions 기타 등등] * Built-in Exceptionì˜ ê²½ìš° ë°œìƒì‹œ Exceptionì´ë¦„ê³¼ ì´ìœ ê°€ ì¶œë ¥ë¨. ==== Handling Exceptions ==== * ì–´ë– í•œ Exceptionë“¤ì— ëŒ€í•´ 개발ìžê°€ ì„ íƒì 으로 다룰 수 있ìŒ. java와 ìœ ì‚¬. {{{ try: x = 1 / 0 except ZeroDivisionError: print(“...â€) }}} * 여러 ê°œì˜ ì˜ˆì™¸ì²˜ë¦¬ëŠ” 튜플로 가능하다. {{{ except (RuntimeError, TypeError, NameError): pass }}} * {{{as}}} 키워드를 ì´ìš©í•´ì„œ ê°ì²´ ì´ìš© 가능 {{{ except OSError as err: print("OS error: {0}".format(err)) }}} * Error ëª…ì„ ì 지 ì•Šê³ {{{except:}}}와 ê°™ì´ ì“°ë©´ ëª¨ë“ Errorì— ëŒ€í•´ 처리. 단, 매우 ì‹ ì¤‘í•˜ê²Œ 사용해야 하며, 다ìŒì²˜ëŸ¼ 메시지를 ì¶œë ¥í•˜ê³ ë‹¤ì‹œ Error를 ì„ ì–¸í•˜ëŠ” ì‹ìœ¼ë¡œ 쓸 수 있ìŒ. {{{ except: print("Unexpected error") raise }}} * {{{else:}}} 구문: try 구문ì—ì„œ exceptionì´ ë°œìƒë˜ì§€ ì•Šì€ ê²½ìš° 실행 * built-in Exception classë“¤ì€ ì¸ìžë¥¼ 넘겨줄 경우 {{{instance.args}}} ë¡œ ì ‘ê·¼ì´ ê°€ëŠ¥í•˜ë©°, {{{__str__()}}}ì€ ì´ {{{.args}}}를 ì¶œë ¥í•´ì¤Œ. {{{ >>> try: ... raise Exception('spam', 'eggs') ... except Exception as inst: ... print(type(inst)) ... print(inst.args) ... print(inst) <class 'Exception'> ('spam', 'eggs') ('spam', 'eggs') }}} ==== Raising Exceptions ==== * {{{raise}}} 구문: 프로그래머가 ì›í•˜ëŠ” Exceptionì„ ì¼ìœ¼í‚¨ë‹¤. * Exceptionì„ ìƒì†ë°›ì€ Class 들만 가능하다 * {{{class className(Exception):}}} ìƒì† 방법 ==== User-defined Exceptions ==== * Exception Class를 ìƒì†í•˜ì—¬ 새로운 Exception class를 만들 수 있다. * {{{__init__()}}}, {{{__str__()}}}ì´ ê¸°ë³¸ì 으로 구현ë˜ì–´ìžˆìœ¼ë‚˜, override 가능. * 가능하면 ‘~Error’ ë¼ëŠ” ì´ë¦„으로 하는 ê²ƒì´ ì¢‹ìŒ. ==== Defining Clean-up Actions ==== * {{{finally:}}} - try ë¬¸ì´ ì™„ì „ížˆ 종료ë˜ê¸° ì§ì „ì— ë°˜ë“œì‹œ 실행ë˜ëŠ” ë‚´ìš©. * except 문으로 사용ìžê°€ ì§€ì •í•œ Exceptionì´ ì•„ë‹Œ 다른 Exceptionì´ ë°œìƒí• 경우 finally ë¬¸ì´ ì‹¤í–‰ëœ ì´í›„ 다시 해당 Exceptionì„ ë°œìƒì‹œí‚¨ë‹¤. * tryë¬¸ì´ ëë‚˜ê³ elseë¬¸ì´ ìžˆìœ¼ë©´ elseë¬¸ì´ ì‹¤í–‰ëœ ë‹¤ìŒì— 실행 ë¨. ==== Predefined Clean-up Actions ==== {{{ with open("myfile.txt") as f: for line in f: print(line, end="") }}} * with ì—ì„œ 나오면 openëœ fileì„ close 해준다. * 조금 ë” ì¼ë°˜ì 으로 설명하ìžë©´, with êµ¬ë¬¸ì„ ë²—ì–´ë‚˜ë©´ ì‚¬ìš©ëœ ê°ì²´ë¥¼ ìžë™ìœ¼ë¡œ ì •ë¦¬í•´ì¤Œ. * {{{__exit__()}}}, {{{__enter__()}}}ê°€ 구현ë˜ì–´ 있는 classì˜ ê²½ìš° with êµ¬ë¬¸ì„ ì‚¬ìš© í• ìˆ˜ 있으며, 다른 built-in classë“¤ë„ êµ¬í˜„ì´ ë˜ì–´ 있ìŒ.