예외: 문법적인 문제는 없으나 실행 중 발생하는 예상치 못한 문제
예외처리: try~except
n1 = 10; n2=0
try:
print(n1/n2)
except:
print('예상치 못한 문제가 발생했습니다.')
print('다음 프로그램이 진행됩니다.')
🔔연습문제: 사용자로부터 숫자 5개를 입력받을 때, 숫자가 아닌 자료형이 입력되면 예외처리하는 프로그램
nums = []
n = 1
while n < 6:
try:
num = int(input('input number: '))
except:
print('예외 발생!')
continue
nums.append(num)
n+=1
print(f'nums: {nums}')
~else: 예외가 발생하면 except 실행, 아니라면 else 실행
finally: 에외 발생과 상관없이 항상 실행
evenList = [] ; oddList = [] ; floatList = [] ; dataList = []
n=1
while n < 6:
try:
data = input('input number: ')
floatNum = float(data)
except:
print('exception raise!!')
print('input number again!!')
continue
else:
if floatNum - int(floatNum) != 0:
print('float number!!')
floatList.append(floatNum)
else:
if floatNum % 2 ==0:
print('even number!!')
evenList.append(floatNum)
else:
print('odd number!!')
oddList.append(floatNum)
n += 1
finally:
dataList.append(data)
print(f'evenList: {evenList}')
print(f'oddList: {oddList}')
print(f'floatList: {floatList}')
print(f'dataList: {dataList}')
💥 5번 반복
N=1
While n < 6
N += 1
*exception: 어떤 예외인지 알려주는 키워드
except Exception as e: #e:별칭
print(f'exception: {e}')
결과값) exception: could not convert string to float: 'SDF'
raise: 예외 발생시킬 수 있는 키워드
🔔연습문제
Q. 사용자가 문자 메시지를 보낼 때 10글자 이하면 SMS 발송, 10글자 초과하면 MMS 발송하는 프로그램
def sendSMS(msg):
if len(msg) > 10:
raise Exception('길이 초과! MMS 전환 후 발송!!', 1)
else:
print('SMS 발송!!')
def sendMMS(msg):
if len(msg)<=10:
raise exception('길이 미달!! SMS전환 후 발송!!', 2)
else:
print('MMS 발송!!')
msg= input('input essage: ')
try:
sendSMS(msg)
except Exception as e: #예외가 발생하면 이쪽으로!
print(f'e: {e.args[0]}')
print(f'e: {e.args[1]}')
if e.args[1] == 1:
sendMMS(msg)
elif e.args[1] == 2:
sendSMS(msg)
사용자 예외 클래스: exception 클래스 상속해서 만들 수 있음
class NotUseZeroException(Exception): #내가 만든 예외 클래스
def __init__(self, n):
super().__init__(f'{n}은 사용할 수 없습니다!!')
def divCalculator(num1, num2):
if num2 == 0:
raise NotUseZeroException(num2) #num2==0일경우NotUseZeroException 발생
else:
print(f'{num1} / {num2} = {num1/num2}')
num1 = int(input('input number1: '))
num2 = int(input('input number2: '))
try:
divCalculator(num1, num2)
except NotUseZeroException as e: #NotUseZeroException이 발생하면 내가 처리할게!
print(e)
🔔연습문제
class PasswordLengthShortException(Exception):
def __init__(self, str):
super().__init__(f'{str}: 길이 5미만!!')
class PasswordLengthLongException(Exception):
def __init__(self, str):
super().__init__(f'{str}: 길이 10초과!!')
class PasswordLengthWrongException(Exception):
def __init__(self, str):
super().__init__(f'{str}: 잘못된 비밀번호!!')
adminPw = input('input admin password: ')
try:
if len(adminPw) < 5:
raise PasswordLengthShortException(adminPw)
elif len(adminPw) > 10:
raise PasswordLengthLongException(adminPw)
elif adminPw != 'admin1234':
raise PasswordLengthWrongException(adminPw)
elif adminPw == 'admin1234':
print('빙고!!')
except PasswordLengthShortException as e1:
print(e1)
except PasswordLengthLongException as e2:
print(e2)
except PasswordLengthWrongException as e3:
print(e3)
텍스트파일
Open() – write() or read() – close()
file = open('D:/pythonTxt/test.txt','w')
strCnt = file.write('Hello World!')
print(f'strCnt : {strCnt}')
file.close()
🔔연습문제
import time
lt = time.localtime()
dateStr = '[' + str(lt.tm_year) + '년' + str(lt.tm_mon) + '월' + str(lt.tm_mday) + '일]'
todaySchedule = input('오늘 일정: ')
file = open('D:/pythonTxt/test.txt','w')
file.write(dateStr + todaySchedule)
file.close()
💥dateStr = '[' + time.strftime('%Y-%m-%d %H:%M:%S %p') + ']'
이 방법이 좀 더 세련!
21시 -> 9시 : %I
🔔연습문제
file = open('D:/pythonTxt/about_python.txt','r',encoding='UTF8')
str = file.read()
str = str.replace('Python','파이썬',2)
print(f'str: {str}')
file =open('D:/pythonTxt/about_python.txt','w',encoding='UTF8'')
file.write(str)
file.close()
파일모드
💥 소수 찾기
inputNumber = int(input('0보다 큰 점수 입력: '))
for number in range(2, inputNumber +1):
flag = True
for n in range(2, number):
if number % n == 0:
flag = False
break
with~as문: 파일 닫기(close)생략 가능
🔔연습문제
Q. 로또번호생성기 프로그램 만들고 파일에 번호 출력
import random
uri = 'D:/pythonTxt/'
def writeNumbers(nums):
for idx, num in enumerate(nums):
with open(uri + 'lotto.txt','a') as f:
if idx < (len(nums) - 2): #idx가 끝에서 2번째보다 작다면
f.write(str(num)+', ')
elif idx == (len(nums) - 2):
f.write(str(num))
elif idx == (len(nums) - 1):
f.write('\n')
f.write('bonus: ' + str(num))
f.write('\n')
rNums = random.sample(range(1, 46), 7)
print(f'rNum: {rNums}')
writeNumbers(rNums)
writelines()
: 리스트, 튜플 데이터를 파일에 쓰기 위한 함수
uri = 'D:/pythonTxt/'
for item in languages:
with open(uri + 'languages.txt', 'a') as f:
f.write(item)
f.write('\n')
writelines()
활용uri = 'D:/pythonTxt/'
with open(uri + 'languages.txt', 'a') as f:
f.writelines(item + '\n' for item in languages)
🔔 연습문제
scoreDic = {'kor':85, 'eng':90, 'mat':92, 'sci':79, 'his':81}
for key in scoreDic.keys():
with open(uri + 'scoreDic.txt','a') as f:
f.write(key + '\t' + str(scoreDic[key]) + '\n')
scoreDic = {'kor':85, 'eng':90, 'mat':92, 'sci':79, 'his':81}
for key in scoreDic.keys():
with open(uri + 'scoreDic.txt','a') as f:
print(scoreDic, file = f)
readline: 한 행만 읽기
uri = 'D:/pythonTxt/'
with open(uri + 'lans.txt', 'r') as f:
line = f.readline()
while line != '':
print(f'line: {line}')
line = f.readline()
readlines: 전체 행 읽기
uri = 'D:/pythonTxt/'
with open(uri + 'lans.txt', 'r') as f:
lanList = f.readlines()
print(f'lanList: {lanList}')
🔔 연습문제
scoreDic = {}
uri = 'D:/pythonTxt/'
with open(uri + 'scores.txt', 'r') as f:
line = f.readline()
while line !='':
tempList = line.split(':') #':'을 구분자로 구분
scoreDic[tempList[0]] = int(tempList[1].strip('\n')) #tempList[0]-key값 / 우변 - value값
print(line, end='') #-> 여기까지만 쓰면 첫째줄 무한반복
line = f.readline() #-> 다음 줄 읽기
print(f'scoreDic: {scoreDic}')
💥strip(): 원하는 문자 제거
💥split(): 특정 문자를 구분자로 자르기
📌
연습문제의 늪에 빠져 허우적.. 시간될 때 문제도 옮겨놔야겠다
\n, \t 도 따옴표 안에 넣기!!!