예외처리 연습문제1
함수
def add(n1,n2):
print('덧셈 연산')
try: #예외처리
n1 = float(n1) #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
# if n2 == 0:
# print('0으로 나눌 수 없습니다.')
# return
try:
print(f'{n1}/{n2} = {n1 / n2}') #
except ZeroDivisionError as e:
print(e)
print('0으로 나눌 수 없습니다.')
실행
import Cal as cc
n1 = input('첫 번째 피연산자 : ')
n2 = input('두 번째 피연산자 : ')
cc.add(n1,n2)
cc.div(n1,n2)
예외처리 연습문제2
소수 구하기
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 #사용자가 고른 숫자가 n으로 나눠서 나머지가 없으면 소수가 아님
break
if flag == False : #소수가 아니라면
raise NotPrimeException(number) #강제로 예외를 발생시키는 raise
else: #소수라면
raise PrimeException(number)
실행
import random
import prime_module as pm
primeNumbers = []
n = 0
while n < 10:
rn = random.randint(1,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
예외처리 연습문제3
영수증 출력
g1Price = 1200; g2Price = 1000; g3Price = 800; g4Price = 2000; g5Price = 900
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('--------------------------------------')
print(f'총 구매 금액 : {totalPrice}원')
print('-------------미결제 항목----------------')
for g in againCntInput.keys():
print(f'상품 : {g}, \t 구매 개수: {againCntInput[g]}')
print('--------------------------------------')
실행
import receipt as cp
g1Cnt = input('goods1 구매 개수 : ')
g2Cnt = input('goods2 구매 개수 : ')
g3Cnt = input('goods3 구매 개수 : ')
g4Cnt = input('goods4 구매 개수 : ')
g5Cnt = input('goods5 구매 개수 : ')
cp.calculator(g1Cnt,g2Cnt,g3Cnt,g4Cnt,g5Cnt)
예외처리 연습문제4
class EmptyDataException(Exception):
def __init__(self, i):
super().__init__(f'{i}is empty!') #자료 중 하나가 비어있으면 에러 발생
def checkInputData(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.m_name = n
self.m_mail = m
self.m_pw = p
self.m_addr = a
self.m_phone = ph
print('Membership complete!!')
def printMemberInfo(self):
print(f'm_name : {self.m_name}')
print(f'm_mail : {self.m_mail}')
print(f'm_pw : {self.m_pw}')
print(f'm_addr : {self.m_addr}')
print(f'm_phone : {self.m_phone}')
실행
import mem
m_name = input('이름 입력 : ')
m_mail = input('메일 입력 : ')
m_pw = input('비밀번호 입력 : ')
m_addr = input('주소 입력 : ')
m_phone = input('연락처 입력 : ')
try:
mem.checkInputData(m_name, m_mail, m_pw, m_addr, m_phone)
newMember = mem.RegistMember(m_name, m_mail, m_pw, m_addr, m_phone) #정상적으로 회원가입이 되는 경우
except mem.EmptyDataException as e:
print(e)
예외처리 연습문제5
import random
class PrivateBank:
def __init__(self, bank, account_name):
self.bank = bank
self.account_name = account_name
while True:
newAccountNo = random.randint(10000,99999)
if bank.isAccount(newAccountNo):
continue
else:
self.account_no = newAccountNo
break
self.totalMoney = 0
bank.addAccount(self)
def printBankInfo(self):
print('*'*40)
print(f'account_name : {self.account_name}')
print(f'account_no : {self.account_no}')
print(f'totalMoney : {self.totalMoney}')
class Bank:
def __init__(self):
self.accounts = {}
def addAccount(self, privateBank):
self.accounts[privateBank.account_no] = privateBank
def isAccount(self,ano): #기존에 있는 계좌번호인지 체크
return ano in self.accounts
def doDeposit(self, ano, m):
pb = self.accounts[ano]
pb.totalMoney = pb.totalMoney + m
def doWithdraw(self, ano, m):
pb = self.accounts[ano]
if pb.totalMoney - m < 0: #출금하는 돈이 입금액보다 크면 안되니까 비교문
raise LackException(pb.totalMoney,m)
pb.totalMoney = pb.totalMoney - m
class LackException(Exception):
def __init__(self,m1,m2):
super().__init__(f'잔고 부족, 잔액 : {m1}, 출금액 : {m2}')
실행
import bank
koreaBank = bank.Bank()
new_account_name = input('통장 개설을 위한 예금주 입력 : ')
myAccount = bank.PrivateBank(koreaBank, new_account_name)
myAccount.printBankInfo()
while True :
selectNumber = int(input('1.입금 2.출금 3.종료'))
if selectNumber == 1:
m = int(input('입금액 입력 : '))
koreaBank.doDeposit(myAccount.account_no, m)
myAccount.printBankInfo()
elif selectNumber ==2:
m = int(input('출금액 입력 : '))
try:
koreaBank.doWithdraw(myAccount.account_no, m)
except bank.LackException as e:
print(e)
finally:
myAccount.printBankInfo()
elif selectNumber ==3:
print('Bye')
break
else:
print('다시 입력하세요')