본문 바로가기

컴퓨터/Python

포맷팅 {}안의 값은 숫자로 표현format 인자의 인덱스로 사용>>> print("{0} is {1}".format("apple", "red"))apple is red>>> print("{0} is {1} or {2}".format("apple", "red", "green"))apple is red or green format의 인자로 키와 값을 지정해 사용 가능>>> print("{item} is {color}".format(item="apple", color="red"))apple is red 사전을 입력으로 받는 경우>>> dic = {"item":"apple", "color":"red"}>>> print("{0[item]} is {0[color]}".format(dic))apple is red0[ite.. 더보기
출력 인자가 여러 개 들어가면 공백으로 구분해서 출력+ 연산자를 이용하면 공백이 없음>>> print(x, 'test')0.2 test>>> print(a + 'this is test')'hello\n'this is test 구분자(sep), 끝라인(end), 출력(file)을 지정할 수 있음>>> import sys>>> print("welcome to", "python", sep="~", end="!", file=sys.stderr) >> f = open('test.txt', 'w')>>> print('file write', file = f)>>> f.close() 화면에 출력할 때 중을 맞추거나 정렬할 때string 객체에서 제공되는 함수를 이용print() 함수에서 제공하는 format 이용>>> fo.. 더보기
repr(), str(), ascii() str은 실제 객체의 값과 다를 수가 있습니다. eval(repr(obj))는 실제 obj와 동일한 값을 생성할 수 있어야 합니다. 하지만 eval(str(obj))는 실제 obj와 동일한 값이 아니거나, 오류를 내는 경우가 있을 수 있습니다.eval()는 string형식으로 받은 문자열을 그대로 실행해준다.ascii()은 아스키에 해당하는 문자열에 대해서 정확히 동일한 값을 반환한다.다만 아스키 이외의 값에 대해서는 백슬래시를 사용한 유니코드값을 반환한다.[출처] Python, str(), repr(), ascii(),eval()|작성자 Youngjae[출처] Python, str(), repr(), ascii(),eval()|작성자 Youngjae>>> f = 0.3 >>> f 0.2999999999.. 더보기
assert 구문 인자로 받은 조건식이 거짓인 경우 AssertError가 발생assert , def foo(x): assert type(x) == int, "Input value must be integer" return x * 10 ret = foo("a") print(ret) Traceback (most recent call last): File "/Users/MGP/Documents/workspace/Python/src/testmodule/__init__.py", line 5, in ret = foo("a") File "/Users/MGP/Documents/workspace/Python/src/testmodule/__init__.py", line 2, in foo assert type(x) == int, "Inpu.. 더보기
raise 구문 의도적으로 예외 발생 raise[Exception] 해당 예외를 발생raise[Exception(data)] 예외 발생 시 관련 데이터를 전달raise 발생된 예외를 상위로 전달 내장 예외 발생 예제>>> def RaiseErrorFunc():raise NameError>>> try:RaiseErrorFunc()except:print("NameError is Catched")NameError is Catched 내장 예외 전달 예제>>> def RaiseErrorFunc():raise NameError("Parameter of NameError")>>> def PropagateError():try:RaiseErrorFunc()except:print("before")raise>>> PropagateErro.. 더보기
사용자정의 예외 >>> class NegativeDivisionError(Exception): >> def PositiveDivide(a, b):if(b > try:ret = PositiveDivide(10, -3)print('10 / 3 = {0}'.format(ret))except NegativeDivisionError as e:print("Error - Second argument of PositiveDivide is ", e.value)except ZeroDivisionError as e:print("Error - ", e.args[0])except:print("Unexpected exception") Error - Second argument o.. 더보기
예외처리 try 블록예외가 예상되는 부분에 작성 except 블록에외발생 시 처리를 담당하는 부분 else 블록예외가 발생하지 않은 경우 수행 finally 블록예외발생과 상관 없이 수행 >>> def divide(a, b):return a/b>>> try:c = divide(5, 0)except:print("Exception is occured!!")Exception is occured!! 처리할 예외를 명시 할 수 있다.>>> def divide(a, b):return a/b>>> try:c = divide(5, 'string')except ZeroDivisionError:print('ZeroDivisonError.')except TypeError:print("TypeError")except:print("I .. 더보기
모듈 임포트 파헤치기 import simpleset을 실행하면 simpleset.pyc 파일이 생성 됨pyc 파일이 생성된 다음 import 구문을 실행하면 별도의 인터프리팅 없이 어트리뷰트를 현재의 이름공간으로 가져오거나 모듈의 이름을 현재 이름공간으로 가져 옴 testmodule.py 생성 후 저장# -*- coding: cp949 -*-print("test module")defaultvalue = 1def printDefaultValue():print(defaultvalue) >>> import testmoduletest module>>> testmodule.printDefaultValue()1 testmodule.py의 코드를 수정 # -*- coding: cp949 -*-print("hello world")defau.. 더보기
모듈 임포트 import 구문을 어디서나 사용>>> def loadMathMod():print("import math")import mathprint(dir(math)) >>> loadMathMod()import math['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isi.. 더보기
모듈 만들기 # -*- coding: cp949 -*-from functools import * def intersect(*ar):"교집합"return reduce(__intersectSC, ar) def __intersectSC(listX, listY):setList = []for x in listX:if x in listY:setList.append(x)return setList def difference(*ar):"차집합"setList = []intersectSet = intersect(*ar)unionSet = union(*ar)for x in unionSet:if not x in intersectSet:setList.append(x)return setListdef union(*ar):"합집합"setList .. 더보기