[파이썬] 중급 문제풀이 (4) 예외처리

greta·2023년 5월 17일
0

1. 산술연산

(calculator.py)
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}')
(ex.py)
import calculator as cc

num1 = input('첫 번째 피연산자 입력: ')
num2 = input('두 번째 피연산자 입력: ')

cc.add(num1,num2)


try와 except를 통해 예외처리를 하는 구문. return과 순서 확인할 것.

(calculator.py)
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으로 나눌 수 없습니다.')
import calculator as cc

num1 = input('첫 번째 피연산자 입력: ')
num2 = input('두 번째 피연산자 입력: ')

cc.div(num1,num2)

나눗셈에서는 n2가 0일때 if n2 == 0을 사용할 수도 있지만,
except ZeroDivisionError으로 사용하였다.

2. 소수 난수

(prime_module.py)
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 == False:
        raise NotPrimeException(number)
    else:
        raise PrimeException(number)
(ex.py)
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

    n += 1

    print(f'primeNumbers: {primeNumbers}')

3. 구매 개수 오류

(calculatorPurchase.py)
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('---------------------------------------------')
(ex.py)
import calculatorPurchase as cp

g1Cnt = input('goods1 구매 개수: ')
g2Cnt = input('goods2 구매 개수: ')
g3Cnt = input('goods3 구매 개수: ')
g4Cnt = input('goods4 구매 개수: ')
g5Cnt = input('goods5 구매 개수: ')

cp.calculator(g1Cnt, g2Cnt, g3Cnt, g4Cnt, g5Cnt)

enumerate, globals()[f'{g}Price'] 의 활용

4. 회원가입 프로그램

(mem.py)
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}')
(ex.py)
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)
    newMember.printMemberInfo()
except mem.EmptyDataException as e:
    print(e)

5. 은행 계좌 개설 및 입/출금 프로그램

(bank.py)
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}')
        print('-' * 40)

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}')
(ex.py)
import bank

koreaBank = bank.Bank()

new_account_name = input('통장 개설을 위한 예금주 입력: ')
myAccount = bank.PrivateBank(koreaBank, new_account_name)
myAccount.printBankInfo()

while True:

    selectNumber = int(input('1.입금,\t 2.출금,\t 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('잘못 입력했습니다. 다시 선택하세요.')

🎅오늘의 한마디

예외처리 부분은 생각보다 어렵지 않지만 아직 클래스와 초기화 등 구조를 만드는 부분에서 어려움을 느낀다. 익숙해질때까지 연습 또 연습.

0개의 댓글