본문 바로가기

Python

Python - Custom Exception (사용자 정의 Exception) #Exception 클래스를 상속한 클래스를 만든다 class CustomException(Exception): #생성할때 value 값을 입력 받는다. def __init__(self, value): self.value = value #생성할때 받은 value 값을 확인 한다. def __str__(self): return self.value #예외를 발생하는 함수 def raise_exception(err_msg): raise CustomException(err_msg) #테스트 해보자 try: raise_exception("Error!!! Error~!!!") except CustomException, e: print e #Error!!! Error~!!! 더보기
Python - inline if 문 "true일때 값" if "조건식" else "false 일때 값" 예제 print ("aa" if True else "bb") #aa print ("aa" if False else "bb") #bb 더보기
Python 어렵게 배우기 - Exercise 39: Dictionaries, Oh Lovely Dictionaries 원문 : http://learnpythonthehardway.org/book/ex39.html python 에는 Dictionary라는 놈이 있다. 간단히 이야기하면 Key : Value 형태로 데이터를 입력하는 Map 같은 놈이다. 사용 양식은 stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2} 뭐 이런식으로 사용 할 수 있다. 예제 코드를 통해 좀더 알아보자 (ex39.py) # create a mapping of state to abbreviation states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } # create a basi.. 더보기
Python - 현재 년, 월, 일, 시, 분, 초 문자열로 표현하기 (yyyymmddhh24miss 형태) datetime.now() 함수와 format 함수를 사용하면 된다. datetime.now()는 현재 시간을 datetime 형태로 반환한다. format 과 관련해서는 http://docs.python.org/2/library/string.html#formatstrings 페이지를 참조하자. from datetime import datetime print "{:%Y%m%d%H%M%S}".format(datetime.now()) 더보기
Python - 문자를 ASCII 코드로, ASCII 코드를 문자로 ord(문자) : 문자의 ASCII 코드를 반환한다.chr(숫자) : 숫자에 대응하는 문자를 반환한다. ord("A") #결과값 65 chr(65) #결과값 A #참고로 #A 는 chr(65) #Z 는 chr(90) #a 는 chr(97) #z 는 chr(122) 더보기
Python 어렵게 배우기 - Exercise 38: Doing Things To Lists 원문 : http://learnpythonthehardway.org/book/ex38.html List를 좀더 사용해 보자 (ex38.py) ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there's not 10 things in that list, let's fix that." stuff = ten_things.split(' ') more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: next_one = more_stuff.pop() print "Adding: ", next_one stuff.. 더보기
Python 어렵게 배우기 - Exercise 37: Symbol Review 원문 : http://learnpythonthehardway.org/book/ex37.html python에서 사용하는 symbol에 대해서 살펴보자 (알아서들...) 더보기
Python 어렵게 배우기 - Exercise 36: Designing and Debugging 원문 : http://learnpythonthehardway.org/book/ex36.html "if", "for", "while" 문을 사용할 때 프로그램의 오류를 줄 일 수 있는 몇가지 방법을 제시 해 본다. Rules For If-Statements 1. 모든 if 문에는 else 문을 작성 할 것2. 모든경우 if 문에 걸리게 되어 있어서 else 문이 실행 될 일이 없을거라 생각되는 경우 else 문에 작성할 내용이 딱히 없을 것이다. 이 경우 에러메세지를 출력하고 프로그램을 종료시키는 코드를 짜 넣자3. if 문을 3단계 이상 중첩해서 사용하지 말자. 가능하면 한단계에서 다 끝내도록 하자. 복잡하다....4. if 문은 문단 처럼 작성하자. if, elif, else 문 앞, 뒤로을 한줄씩 띄.. 더보기