exception_ex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
def handling_exception():
"""
예외 ㅓ리 연습
:return:
"""
lst=[]
try:
# 오류 발생 가능 코드 블록을 try
#lst[3]=1
4/2
int("1234")
except IndexError as e:
print("인덱스 범위 오류")
print("Error:", e, type(e))
except ZeroDivisionError as e:
print("0으로는 나눌 수 없습니다.")
print("Error:", e, type(e))
except ValueError as e:
print("정수 변환 실패")
print("오류:",e,type(e))
except Exception as e:
""" Exception은 모든 오류를 처리하기 때문에
가장 마지막 except로 사용한다 ( 순서 유의 ) """
print("Error")
print("Error:",e,type(e))
else: # 예외 없이 블록이 수행되었을 때
print("정상 실행 완료")
finally:
print("예외 처리 완료")
def raise_exception():
"""
강제 예외 발생 예제
:return:
"""
def beware_dog(animal):
"""
만약 animol == "dog" 면 출입 제한
아니면 "어서오세요"
:param animal:
:return:
"""
if animal=="dog":
# 예외 발생 : raise
raise RuntimeError("강아지는 출입을 제한합니다.")
else:
print("어서 오세요:",animal)
try:
beware_dog("cat")
beware_dog("cow")
beware_dog("dog") # 내부에서 raise로 강제 예외 발생
except RuntimeError as e:
print(e,type(e))
finally:
print("예외 처리 완료")
if __name__ == "__main__":
#handling_exception()
raise_exception()
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
fileio_ex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
# 파일 모드 정리
# 파일 종류 : t(text, default(t), b(binary)
# 작업 종류 r(read, default(t), w(write), a(append)
def write_text_ex():
"""
텍스트 파일 저장 예제
:return:
"""
write_size=f.write("Life is too short, you need Python\n")
print("write_size",write_size)
f.close()
def write_text_ex2():
"""with ~ as 를 이용한 자동 리소스 닫기"""
write_size=f.write("Life is too short, you need Python\n")
# with 블록 종료 이후 자동으로 리소스 해제
print("f는 열려있나?,",f.close()) # 안전성 확보
def read_text_ex():
"""
:return:
"""
text = f.read()
print("scv:",text)
f.close() # 반드시 닫아줍니다
def read_text_ex2():
"""
한 라인씩 읽어와서 가공
:return:
"""
while True: # 몇 라인인지 알 수 없으니 무한 루프
line=f.readline()
if not line:
break
#print(line)
info = line.replace("\n","").split(",")
member={
"name":info[0],
"number":info[1],
"position":info[3]
}
print("MEMBERS",members)
# 연습문제
# sample 디렉터리 안쪽에 rose-flower.jpeg가 있음
# binary 모드로 열어서
import pickle
def pickle_dump():
def pickle_load():
"""
피클 불러오기
:return:
"""
# 파일 내부에 피클이 몇 개 있는지 알 수 없으므로
while True:
try:
print(pickle.load(f))
except EOFError:
print("피클은 더이상 없음")
break
if __name__ == "__main__":
#write_text_ex() # 텍스트 파일 저장 예제
#write_text_ex2() # with ~ as 를 이용한 리소스 해제
#read_text_ex() # 텍스트 파일 read 예제
#read_text_ex2()
pickle_dump()
pickle_load()
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
datetime_ex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
import datetime # 모듈 임포트
def get_datetime():
"""
날짜와 시간의 획득
:return:
"""
# 현재 날짜
print("현재 날짜와 시간:",dt)
print(type(dt))
# 생성자를 이용한 날짜 시간 정보의 획득
# 연 월 일 시 분 초 마이크로 세컨드 순으로 매개변수 부여
# 단 최소 연 월 일은 필요
past = datetime.datetime(1999,12,31)
print("PAST:",past)
# 요일의 확인 weekday()
print("오늘은 무슨 요일?",dt.weekday())
# 날짜 정보의 추출
print("NOWDATE:",nowdate,type(nowdate))
nowtime=dt.time()
print("NOWTIME:",nowtime,type(nowtime))
print(dt>past) #더 최근 시간이 큰 값
def timedelta_ex():
"""
날짜/시간 차이값 : timedelta 객체
:return:
"""
past = datetime.datetime(1999,12,31) # 과거
diff = now - past
print("DIFF:",diff,type(diff))
# 미래로 가 보기
days=datetime.timedelta(100,0,0)
print("DAYS",days)
print("FUTURE(100일 후):",now+days)
def format_date():
print("now",now)
#date_str = now
print("format:",now.strftime("%Y/%m/%d"))
import locale
locale.setlocale(locale.LC_ALL, "ko_KR.UTF-8")
# Windows 로케일 정보가 맞지 않을 때의 처리
print("format:", now.strftime("%Y년 %m월 %d일"))
# 문자열로 저장된 날짜 정보를 다시 datetime 형태로 변환
s= "2012-09-24 14:00"
dt= datetime.datetime.strptime(s, "%Y-%m-%d %H:%M")
print("CONWERTED:",dt,type(dt))
if __name__ == "__main__":
#get_datetime()
#timedelta_ex()
format_date()
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
point.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
# point.py
class Point:
instance_count = 0
def __init__(self,x=0,y=0): # 생성자, 초기화 코드
self.x = x
self.y = y
Point.instance_count += 1
# 소멸자, 정리 코드
def __del__(self):
Point.instance_count -=1
def setX(self, x):
self.x = x
def getX(self):
return self.x
def setY(self, y):
self.y = y
def getY(self):
return self.y
def bound_class_method():
p=Point() # 인스턴스 객체 생성
p.setX(10)
p.setY(20)
print(p)
def unbound_class_method():
p = Point()
if __name__ == "__main__":
#bound_class_method()
unbound_class_method()
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
paint.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
from point import Point
def main():
unbound_class_method()
def unbound_class_method():
p = Point()
Point.set_x(p, 10) # 객체를 첫 번째 인자에 할당하고 있음에 유의
Point.set_y(p, 10)
print((Point.get_x(p), Point.get_y(p), sep = ','))
def bound_class_method():
p = Point() # Point 인스턴스 객체 생성
p.set_x(10)
p.set_y(10)
print(p.get_x(),p.get_y(), sep = ',')
if __name__ == "__main__":
main()
p = Point(10, 10)
print("P: x={}, y={}".format(p.getX(),p.getY()))
print("Point instance count", Point.instance_count)
p2 = Point(20, 20)
print("Point instance count:", Point.instance_count)
del p2 # 소멸자 호출
print("Point instance count:",Point.instance_count)
print("P1:",p)
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
'딥러닝 기반 영상인식 개발 전문가 과정 > C언어, Python, 자료구조' 카테고리의 다른 글
7월24일 파이썬 텐서플로우 기반 머신러닝 기초 (0) | 2019.07.24 |
---|---|
7월23일 파이썬 str메서드, 오버로딩, jupyter, Pandas (0) | 2019.07.23 |
7월22일 파이썬 날짜와 시간, 모듈, 클래스 (0) | 2019.07.22 |
7월22일 파이썬 예외처리, 파일, Using Pickle (0) | 2019.07.22 |
7월19일 파이썬 예제 코드 (0) | 2019.07.19 |