Toggle menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Python3Tutorial: Difference between revisions

From ZeroWiki
imported>lyuha
No edit summary
imported>lyuha
No edit summary
Line 117: Line 117:
=== Using the Python Interpreter ===
=== Using the Python Interpreter ===
=== An Informal Introduction to Python ===
=== An Informal Introduction to Python ===
*
#
: 주석
==== Using Python as a Calculator ====
==== Using Python as a Calculator ====
===== Numbers =====
===== Numbers =====

Revision as of 09:08, 26 June 2014

개요

진행사항

  • ~~An Informal Introduction to Python~~
    • ~~Using Python as a Calculator~~
    • ~~Numbers~~
    • ~~Strings~~
    • ~~Lists~~
    • ~~First Steps Towards Programming~~
  • More Control Flow Tools
    • if Statements
    • for Statements
    • The range() Function
    • break and continue Statements, and else Clauses on Loops
    • pass Statements
    • Defining Functions
    • More on Defining Functions
    • Default Argument Values
    • Keyword Arguments
    • Arbitrary Argument Lists
    • Unpacking Argument Lists
    • Lambda Expressions
    • Documentation Strings
    • Function Annotations
    • Intermezzo: Coding Style
  • Data Structures
    • More on Lists
    • Using Lists as Stacks
    • Using Lists as Queues
    • List Comprehensions
    • Nested List Comprehensions
    • The del statement
    • Tuples and Sequences
    • Sets
    • Dictionaries
    • Looping Techniques
    • More on Conditions
    • Comparing Sequences and Other Types
  • Modules
    • More on Modules
    • Executing modules as scripts
    • The Module Search Path
    • “Compiled” Python files
    • Standard Modules
    • The dir() Function
    • Packages
    • Importing * From a Package
    • Intra-package References
    • Packages in Multiple Directories
  • Input and Output
    • Fancier Output Formatting
    • Old string formatting
    • Reading and Writing Files
    • Methods of File Objects
    • Saving structured data with json
  • Errors and Exceptions
    • Syntax Errors
    • Exceptions
    • Handling Exceptions
    • Raising Exceptions
    • User-defined Exceptions
    • Defining Clean-up Actions
    • Predefined Clean-up Actions
  • Classes
    • A Word About Names and Objects
    • Python Scopes and Namespaces
    • Scopes and Namespaces Example
    • A First Look at Classes
    • Class Definition Syntax
    • Class Objects
    • Instance Objects
    • Method Objects
    • Random Remarks
    • Inheritance
    • Multiple Inheritance
    • Private Variables
    • Odds and Ends
    • Exceptions Are Classes Too
    • Iterators
    • Generators
    • Generator Expressions
  • Brief Tour of the Standard Library
    • Operating System Interface
    • File Wildcards
    • Command Line Arguments
    • Error Output Redirection and Program Termination
    • String Pattern Matching
    • Mathematics
    • Internet Access
    • Dates and Times
    • Data Compression
    • Performance Measurement
    • Quality Control
    • Batteries Included
  • Brief Tour of the Standard Library – Part II
    • Output Formatting
    • Templating
    • Working with Binary Data Record Layouts
    • Multi-threading
    • Logging
    • Weak References
    • Tools for Working with Lists
    • Decimal Floating Point Arithmetic
  • What Now?
  • Interactive Input Editing and History Substitution
    • Tab Completion and History Editing
    • Alternatives to the Interactive Interpreter
  • Floating Point Arithmetic: Issues and Limitations
    • Representation Error

내용

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이랑 동일하게 적용.
>>> 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
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}}}, 기타 등등

    • 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들도 구현이 되어 있음.