[연습문제] 예외처리(01)
def add(n1, n2):
print('덧셈 연산')
try:
n1 = float(n1)
except:
print('첫 번째 피연산자: 숫자가 아닙니다')
return
try:
n2 = float(n2)
except:
print('두 번째 피연산자: 숫자가 아닙니다')
return
print(f'{n1} + {n2} = {n1 + n2}')
def sub(n1, n2):
print('뺄셈 연산')
try:
n1 = float(n1)
except:
print('첫 번째 피연산자: 숫자가 아닙니다')
return
try:
n2 = float(n2)
except:
print('두 번째 피연산자: 숫자가 아닙니다')
return
print(f'{n1} - {n2} = {n1 - n2}')
def mul(n1, n2):
print('곱셈 연산')
try:
n1 = float(n1)
except:
print('첫 번째 피연산자: 숫자가 아닙니다')
return
try:
n2 = float(n2)
except:
print('두 번째 피연산자: 숫자가 아닙니다')
return
print(f'{n1} * {n2} = {n1 * n2}')
def div(n1, n2):
print('나눗셈 연산')
try:
n1 = float(n1)
except:
print('첫 번째 피연산자: 숫자가 아닙니다')
return
try:
n2 = float(n2)
except:
print('두 번째 피연산자: 숫자가 아닙니다')
return
try:
print(f'{n1} / {n2} = {n1 / n2}')
except ZeroDivisionError as e:
print(e)
print('0으로 나눌 수 없습니다')
def mod(n1, n2):
print('나머지 연산')
try:
n1 = float(n1)
except:
print('첫 번째 피연산자: 숫자가 아닙니다')
return
try:
n2 = float(n2)
except:
print('두 번째 피연산자: 숫자가 아닙니다')
return
try:
print(f'{n1} % {n2} = {n1 % n2}')
except ZeroDivisionError as e:
print(e)
print('0으로 나눌 수 없습니다')
def flo(n1, n2):
print('몫 연산')
try:
n1 = float(n1)
except:
print('첫 번째 피연산자: 숫자가 아닙니다')
try:
n2 = float(n2)
except:
print('두 번째 피연산자: 숫자가 아닙니다')
try:
print(f'{n1} // {n2} = {n1 // n2}')
except ZeroDivisionError as e:
print(e)
print('0으로 나눌 수 없습니다')
def exp(n1, n2):
print('거듭제곱 연산')
try:
n1 = float(n1)
except:
print('첫 번째 피연산자: 숫자가 아닙니다')
try:
n2 = float(n2)
except:
print('두 번째 피연산자: 숫자가 아닙니다')
print(f'{n1} ** {n2} = {n1 ** n2}')
import calculator as cc
num1 = input('첫 번째 피연산자 입력: ')
num2 = input('두 번째 피연산자 입력: ')
cc.add(num1, num2)
cc.sub(num1, num2)
cc.mul(num1, num2)
cc.div(num1, num2)
cc.mod(num1, num2)
cc.flo(num1, num2)
cc.exp(num1, num2)
[연습문제] 예외처리(02)
class NotPrimeException(Exception):
def __init__(self, n):
super().__init__(f'{n} is not prime number')
class PrimeException(Exception):
def __init__(self, n):
super().__init__(f'{n} is prime number')
def isPrime(number):
flag = True
for n in range(2, number):
if number % n == 0:
flag = False
break
if flag == True:
raise PrimeException(number)
else:
raise NotPrimeException(number)
import random
import primenum as pm
primeNumbers = []
n = 0
while n < 10:
rn = random.randint(2, 1000)
if rn not in primeNumbers:
try:
pm.isPrime(rn)
except pm.NotPrimeException as e:
print(e)
continue
except pm.PrimeException as e:
print(e)
primeNumbers.append(rn)
else:
print(f'{rn} is overlap number')
continue
n += 1
print(primeNumbers)
- 모듈에서 break, raise 자꾸 잊어버림 주의
- try - except 구문 사용 방법 아직도 헷갈림 ㅠ
[연습문제] 예외처리(03)
g1Price = 1200; g2Price = 1000; g3Price = 800
g4Price = 2000; g5Price = 900
def formatedNum(n):
return format(n, ',')
def calculator(*gcs):
gcsDic = {}
againCntInput = {}
for idx, gc in enumerate(gcs):
try:
gcsDic[f'g{idx+1}'] = int(gc)
except Exception as e:
againCntInput[f'g{idx+1}'] = gc
print(e)
totalPrice = 0
for g in gcsDic.keys():
totalPrice += globals()[f'{g}Price'] * gcsDic[g]
print('-'*30)
print(f'총 구매 금액: {formatedNum(totalPrice)}원')
print('-'*10 + '미결제 항목' + '-'*10)
for g in againCntInput.keys():
print(f'상품: {g}, \t 구매 개수: {againCntInput[g]}')
print('-'*30)
import calculator as cc
g1Cnt = input('goods1 구매 개수: ')
g2Cnt = input('goods2 구매 개수: ')
g3Cnt = input('goods3 구매 개수: ')
g4Cnt = input('goods4 구매 개수: ')
g5Cnt = input('goods5 구매 개수: ')
cc.calculator(g1Cnt, g2Cnt ,g3Cnt, g4Cnt, g5Cnt)
- 입력될 값의 개수를 모를 때, *를 사용하면 된다 (자세한건 뒤에 나오겠지)
- 문제풀이로는 확실히 기억하기가 어려운 딕셔너리 사용법
- 따라쓰고 해석하고 넘어가기
[연습문제] 예외처리(04)
class EmptyDataException(Exception):
def __init__(self, i):
super().__init__(f'{i} is empty')
def checkDataInput(n, m, p, a, ph):
if n == '':
raise EmptyDataException('name')
elif m == '':
raise EmptyDataException('mail')
elif p == '':
raise EmptyDataException('password')
elif a == '':
raise EmptyDataException('address')
elif ph == '':
raise EmptyDataException('phone')
class RegistMember:
def __init__(self, n, m, p, a, ph):
self.name = n
self.mail = m
self.password = p
self.address = a
self.phone = ph
print('Membership completed')
def printMember(self):
print(f'name: {self.name}')
print(f'mail: {self.mail}')
print(f'password: {self.password}')
print(f'address: {self.address}')
print(f'phone: {self.phone}')
import member as mem
name = input('이름 입력: ')
mail = input('메일 주소 입력: ')
pw = input('비밀번호 입력: ')
adr = input('주소 입력: ')
phone = input('연락처 입력: ')
try:
mem.checkDataInput(name, mail, pw, adr, phone)
newMem = mem.RegistMember(name, mail, pw, adr, phone)
mem.RegistMember.printMember(newMem)
except mem.EmptyDataException as e:
print(e)
- 강의 들으면서 한번 써보고, 혼자서 해보고 모르는게 있으면 다시 보고 반복
- 심각하게 어려운 수준은 아니였으나 잔실수가 많아 에러가 자주 발생
- exception 쓸 때 raise 잊지 말 것
- 실행 파일에서 try - except를 안써주면, 오류가 난다! except 뒤에 꼭 만들어둔 Exception 사용해서 print(e) 해줄 것
[연습문제] 예외처리(05)
- 혼자 시도(!) 했으나, 예외처리 잘되는지 확인하기도 전에
totalMoney 값에 더하는 것도, 최종 출력하는 것도 안됨 ㅠㅠ
- 오늘은 영상 보고 내일 다시 시도!
class NotEnoughBalance(Exception):
def __init__(self, b, w):
super().__init__(f'잔고 부족!!, 잔액: {b}, 출금액: {w}')
class Transaction:
totalMoney = 0
def deposit(n):
totalMoney += n
return totalMoney
def withdrawal(n):
if totalMoney >= n:
totalMoney -= n
else:
NotEnoughBalance(totalMoney, n)
def transactionOver():
print('Bye~')
def printUserInfo(n, a, m):
print(f'account_name: {n}')
print(f'account_no: {a}')
print(f'totalMoney: {m}')
import random
import banking as bk
userName = input('통장 개설을 위한 예금주 입력: ')
account = random.randint(10000,99999)
totalMoney = 0
print('-' * 40)
bk.Transaction.printUserInfo(userName, account, totalMoney)
print('-' * 40)
userSelect = int(input('1. 입금,\t2.출금,\t3.종료\t'))
if userSelect == 1:
userDeposit = int(input('입금액 입력: '))
bk.Transaction.deposit(userDeposit)
print('-' * 40)
bk.Transaction.printUserInfo(userName, account, totalMoney)