for i in range(5):
try:
print(10 / i)
except ZeroDivisionError:
print("Not divided by 0")
Not divided by 0
10.0
5.0
3.3333333333333335
2.5
for i in range(5):
try:
result = 10 / i
except ZeroDivisionError:
print("Not divided by 0")
else:
print(10 / i)
Not divided by 0
10.0
5.0
3.3333333333333335
2.5
try:
for i in range(1, 5):
result = 10 / i
print(result)
except ZeroDivisionError:
print("Not divided by 0")
finally:
print("종료되었습니다.")
10.0
5.0
3.3333333333333335
2.5
종료되었습니다.
while True:
value = input("변환할 정수 값을 입력해주세요.")
for digit in value:
if digit not in "0123456789":
raise ValueError("숫자 값을 입력하지 않으셨습니다.")
print("정수 값으로 변환된 숫자 - ", int(value))
변환할 정수 값을 입력해주세요.123
정수 값으로 변환된 숫자 - 123
변환할 정수 값을 입력해주세요.4-2진도준
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-fa6952095a0f> in <module>
3 for digit in value:
4 if digit not in "0123456789":
----> 5 raise ValueError("숫자 값을 입력하지 않으셨습니다.")
6 print("정수 값으로 변환된 숫자 - ", int(value))
ValueError: 숫자 값을 입력하지 않으셨습니다.
def get_binary_number(decimal_number):
assert isinstance(decimal_number, int)
return bin(decimal_number)[2:]
print(get_binary_number(123))
print(get_binary_number("123"))
1111011
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-13-1d391be279b8> in <module>
4
5 print(get_binary_number(123))
----> 6 print(get_binary_number("123"))
<ipython-input-13-1d391be279b8> in get_binary_number(decimal_number)
1 def get_binary_number(decimal_number):
----> 2 assert isinstance(decimal_number, int)
3 return bin(decimal_number)[2:]
4
5 print(get_binary_number(123))
AssertionError:
from google.colab import drive
drive.mount('/content/drive')
Mounted at /content/drive
folder_path = "/content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC/Pre_Course/Codes/"
f = open(folder_path+"i_have_a_dream.txt", "r")
contents = f.read()
print(contents)
f.close()
I Have a Dream, a song to sing
To help me cope, with anything
If you see the wonder, of a fairy tale
You can take the future, even if you fail
I believe in angels
Something good in everything I see
I believe in angels
When I know the time is right for me
I'll cross the stream, I Have a Dream
I Have a Dream, a fantasy
To help me through, reality
And my destination, makes it worth the while
Pushin' through the darkness, still another mile
I believe in angels
Something good in everything I see
I believe in angels
When I know the time is right for me
I'll cross the stream, I Have a Dream
I'll cross the stream, I Have a Dream
I Have a Dream, a song to sing
To help me cope, with anything
If you see the wonder, of a fairy tale
You can take the future, even if you fail
I believe in angels
Something good in everything I see
I believe in angels
When I know the time is right for me
I'll cross the stream, I Have a Dream
I'll cross the stream, I Have a Dream
folder_path = "/content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC/Pre_Course/Codes/"
with open(folder_path+"i_have_a_dream.txt", "r") as my_file:
contents = my_file.read()
print(type(contents), contents)
<class 'str'> I Have a Dream, a song to sing
To help me cope, with anything
If you see the wonder, of a fairy tale
You can take the future, even if you fail
I believe in angels
Something good in everything I see
I believe in angels
When I know the time is right for me
I'll cross the stream, I Have a Dream
I Have a Dream, a fantasy
To help me through, reality
And my destination, makes it worth the while
Pushin' through the darkness, still another mile
I believe in angels
Something good in everything I see
I believe in angels
When I know the time is right for me
I'll cross the stream, I Have a Dream
I'll cross the stream, I Have a Dream
I Have a Dream, a song to sing
To help me cope, with anything
If you see the wonder, of a fairy tale
You can take the future, even if you fail
I believe in angels
Something good in everything I see
I believe in angels
When I know the time is right for me
I'll cross the stream, I Have a Dream
I'll cross the stream, I Have a Dream
folder_path = "/content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC/Pre_Course/Codes/"
with open(folder_path+"i_have_a_dream.txt", "r") as my_file:
i = 0
while True:
line = my_file.readline()
if not line:
break
print(str(i) + " === " + line.replace("\n", "")) # 한 줄씩 값 출력
i += 1
0 === I Have a Dream, a song to sing
1 === To help me cope, with anything
2 === If you see the wonder, of a fairy tale
3 === You can take the future, even if you fail
4 === I believe in angels
5 === Something good in everything I see
6 === I believe in angels
7 === When I know the time is right for me
8 === I'll cross the stream, I Have a Dream
9 === I Have a Dream, a fantasy
10 === To help me through, reality
11 === And my destination, makes it worth the while
12 === Pushin' through the darkness, still another mile
13 === I believe in angels
14 === Something good in everything I see
15 === I believe in angels
16 === When I know the time is right for me
17 === I'll cross the stream, I Have a Dream
18 === I'll cross the stream, I Have a Dream
19 === I Have a Dream, a song to sing
20 === To help me cope, with anything
21 === If you see the wonder, of a fairy tale
22 === You can take the future, even if you fail
23 === I believe in angels
24 === Something good in everything I see
25 === I believe in angels
26 === When I know the time is right for me
27 === I'll cross the stream, I Have a Dream
28 === I'll cross the stream, I Have a Dream
folder_path = "/content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC/Pre_Course/Codes/"
with open(folder_path+"i_have_a_dream.txt", "r") as my_file:
contents = my_file.read()
line_list = contents.split("\n") # 한 줄씩 분리한 리스트
word_list = contents.split(" ") # 빈 칸 기준으로 단어 분리한 리스트
print(" Total Number of Characters:", len(contents))
print(" Total Number of Lines:", len(line_list))
print(" Total Number of Words:", len(word_list))
Total Number of Characters: 959
Total Number of Lines: 29
Total Number of Words: 171
folder_path = "/content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC/Pre_Course/Codes/"
f = open(folder_path+"i_have_a_dream.txt", "w", encoding="utf8")
for i in range(1, 11):
data = "%d번째 줄입니다.\n" % i
f.write(data)
f.close()
folder_path = "/content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC/Pre_Course/Codes/"
with open(folder_path+"i_have_a_dream.txt", "a", encoding="utf8") as f:
for i in range(1, 11):
data = "%d번째 줄입니다.\n" % i
f.write(data)
import os
os.mkdir("log")
# 디렉토리가 있는지 미리 확인하고 없으면 만들기
if not os.path.isdir("log"):
os.mkdir("log")
import pathlib
import sys
sys.path.append("/content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC/Pre_Course/Codes")
%cd /content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC
cwd = pathlib.Path.cwd()
print(cwd)
print(cwd.parents)
print(list(cwd.parents))
print(list(cwd.glob("*")))
%cd /content
/content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC
/content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC
<PosixPath.parents>
[PosixPath('/content/drive/MyDrive/Colab Notebooks'), PosixPath('/content/drive/MyDrive'), PosixPath('/content/drive'), PosixPath('/content'), PosixPath('/')]
[PosixPath('/content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC/Pre_Course')]
/content
import os
log_path = "/content/drive/MyDrive/Colab Notebooks/NAVER_AI_BC/Pre_Course/Materials/log"
if not os.path.isdir(log_path):
os.mkdir(log_path)
if not os.path.exists(log_path+"/count_log.txt"):
f = open(log_path+"/count_log.txt", "w", encoding="utf8")
f.write("기록이 시작됩니다\n")
f.close()
with open(log_path+"/coung_log.txt", "a", encoding="utf8") as f:
import random, datetime
for i in range(1, 11):
stamp = str(datetime.datetime.now())
value = random.random() * 1000000
log_line = stamp + "\t" + str(value) + "값이 생성되었습니다." + "\n"
f.write(log_line)
import pickle
f = open("list.pickle", "wb") # wb: write byte, pickle은 byte 형식으로 데이터를 읽고 씀
test = [1, 2, 3, 4, 5]
pickle.dump(test, f)
f.close()
f = open("list.pickle", "rb") # rb: read byte
test_pickle = pickle.load(f)
print(test_pickle)
f.close()
[1, 2, 3, 4, 5]
import pickle
class Multiply(object):
def __init__(self, multiplier):
self.multiplier = multiplier
def multiply(self, number):
return number * self.multiplier
my_multiply = Multiply(5)
print(my_multiply.multiply(10))
f = open("my_multiply_object.pickle", "wb")
pickle.dump(my_multiply, f)
f.close()
f = open("my_multiply_object.pickle", "rb")
my_multiply_pickle = pickle.load(f)
my_multiply_pickle.multiply(5)
50
25
내용이 다소 어려우니 참고:
로그를 남긴다(logging)는 것은, 프로그램이 실행되는 동안 일어나는 정보에 대한 기록을 남기는 것
유저의 접근, 프로그램의 예외 처리, 특정 함수의 사용 등
Console 화면에 출력하거나, 파일 또는 DB에 남기는 방식을 사용
로그 기록을 분석하여 의미있는 결과를 도출할 수 있음
실행시점/개발시점에서 남겨야 하는 기록이 다름
print vs logging
Console 창에만 남는 print 기록은 분석시 사용이 불가
떄로는 개발단계/운영단계 등 레벨 별 기록을 따로 남길 필요도 있으며, 모듈 별로 별도 logging이 필요한 경우도 있음
이러한 기능을 체계적으로 지원하는 파이썬 기본 로그 관리 모듈이 "logging"
import logging
logging.debug("틀렸잖아!")
logging.info("확인해")
logging.warning("조심해!!")
logging.error("에러났어!!!")
logging.critical("ㅈ됐어...")
import logging
logger = logging.getLogger("main") # Logger 선언
stream_handler = logging.StreamHandler() # Logger의 output 방법 선언
logger.addHandler(stream_handler) # Logger의 output 등록
logger.setLevel(logging.DEBUG)
logger.debug("틀렸잖아!")
logger.info("확인해")
logger.warning("조심해!!")
logger.error("에러났어!!!")
logger.critical("ㅈ됐어...")
logger.setLevel(logging.CRITICAL)
logger.debug("틀렸잖아!")
logger.info("확인해")
logger.warning("조심해!!")
logger.error("에러났어!!!")
logger.critical("ㅈ됐어...")
import configparser
config = configparser.ConfigParser()
config.sections()
config.read("example.cfg")
config.sections()
for key in config["SectionOne"]:
print(key)
config["SectionOne"]["status"]
import argparse
parser = argparse.ArgumentParser(description="Sum Two Integers.")
# 짧은 이름, 긴 이름, 표시명, help 설명, argument type 순
parser.add_argument("-a", "--a_value", dest="A_value", help="A integers", type=int)
parser.add_argument("-b", "--b_value", dest="B_value", help="B integers", type=int)
args = parser.parse_args()
print(args)
print(args.a)
print(args.b)
print(args.a + args.b)
def main():
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N', help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N', help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.01, metavar='LR', help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.5, metavar='M', help='SGD momentum (default: 0.5)')
parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)')
parser.add_argument('--save-model', action='store_true', default=False, help='For Saving the current Model')
args = parser.parse_args()
if __name__ == '__main__':
main()
formatter = logging.Formatter("%(asctime)s %(levelname)s %(process)d %(message)s")
logging.config.fileConfig("logging.conf")
logger = logging.getLogger()
logger.info("Open file {0}".format("customers.csv"))
try:
with open("customers.csv", "r") as customer_data:
customer_reader = csv.reader(customer_data, delimiter=",", quotechar='"')
for customer in customer_reader:
if customer[10].upper() == "USA":
logger.info("ID {0} added".format(customer[0],))
customer_USA_only_list.append(customer)
except FileNotFoundError as e:
logger.error("File NOT fount {0}".format(e,))