[9일차] 파이썬 중급문풀5~6

하은·2023년 10월 27일
0

예외처리

예외처리 프로그래밍

1. 사용자가 입력한 수사를 이용해서 산술연산 결과를 출력하는 모듈을 만들되, 예상하는 예외에 대한 예외처리 코드를 작성해보자.

  • calculator
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

#    if n2 == 0:
#        print('0으로 나눌 수 없습니다.')
#        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

    if n2 == 0:
        print('0으로 나눌 수 없습니다.')
        return

    print(f'{n1} % {n2} = {n1 % n2}')

def flo(n1, n2):
    print('몫 연산')
    try:
        n1 = float(n1)
    except:
        print('첫번째 피연산자는 숫자가 아닙니다.')
        return

    try:
        n2 = float(n2)
    except:
        print('두번째 피연산자는 숫자가 아닙니다.')
        return

    if n2 == 0:
        print('0으로 나눌 수 없습니다.')
        return

    print(f'{n1} // {n2} = {n1 // n2}')

def exp(n1, n2):
    print('거듭제곱 연산')
    try:
        n1 = float(n1)
    except:
        print('첫번째 피연산자는 숫자가 아닙니다.')
        return

    try:
        n2 = float(n2)
    except:
        print('두번째 피연산자는 숫자가 아닙니다.')
        return

    print(f'{n1} ** {n2} = {n1 ** n2}')
  • ex
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)

? 2. 1부터 1000까지의 소수인 난수를 10개 생성하되, 소수가 아니면 사용자 예외가 발생하도록 프로그램을 만들어보자

  • prime_module
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
import random
import prime_module 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(f'primeNumbers: {primeNumbers}')

? 3. 상품구매에 따른 '총 구매 금액'을 출력하되, 다음과 같이 개수가 잘못 입력된 겨우 별도로 출력하도록 프로그램을 만들어보자

  • calculatorPurchase
g1Price = 1200; g2Price = 1000;
g3Price = 800; g4Price = 2000; g5Price = 900

def formatedNumber(n):
    return format(n, ',')
def calculator(*gcs): # *는 개수가 안 정해졌을 때

    gcsDic = {} #개수가 정상적으로 입력된 상품의 목록
    againCntInput = {} #재결제 돼야하는 것

    for idx, gc in enumerate(gcs):
        try:
            gcsDic[f'g{idx+1}'] = int(gc) #idx가 0부터 시작. 상품 1번이라는 key값에 gc숫자 바꾼 값을 넣어줌. 상품1번에는 구매개수 몇개, 2에는 ~

        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]
                        # 가격     *       개수
                        # 변수명 찾는 방법 = globals 함수

    print('-' * 40)
    print(f'총 구매 금액: {formatedNumber(totalPrice)}원')
    print('-' * 15, '미결제항목', '-'* 15)
    for g in againCntInput.keys():
        print(f'상품: {g}, \t 구매개수: {againCntInput[g]}')
    print('-' * 40)
  • ex
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)

-->
goods1 구매개수: 1
goods2 구매개수: m
goods3 구매개수: 2
goods4 구매개수: 3
goods5 구매개수: 1
invalid literal for int() with base 10: 'm'
----------------------------------------
총 구매 금액: 9,700원
--------------- 미결제항목 ---------------
상품: g2, 	 구매개수: m
----------------------------------------

? 4. 회원가입 프로그램을 만들되 입력하지 않은 항목이 있는 경우 에러메시지를 출력하는 프로그램을 만들어보자

  • mem
class EmptyDataException(Exception):
    def __init__(self, i): #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_add = 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_add: {self.m_add}')
        print(f'm_phone: {self.m_phone}')
  • ex
import mem

m_name = input('이름 입력: ')
m_mail = input('메일주소 입력: ')
m_pw = input('비밀번호 입력: ')
m_add = input('주소 입력: ')
m_phone = input('연락처 입력: ')

try:
    mem.checkInputData(m_name, m_mail, m_pw, m_add, m_phone)
    newMember = mem.RegistMember(m_name, m_mail, m_pw, m_add, m_phone)
    newMember.printMemberInfo()
except mem.EmptyDataException as e:
    print(e)

5. 다음과 같은 은행계좌 개설 및 입/출금 프로그램을 만들어보자

  • bank
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.addAcoount(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 addAcoount(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
import bank

koreaBank = bank.Bank()

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

while True:

    selectNum = int(input('1.입금, \t2.출금, \t3.종료'))
    if selectNum == 1:
        m = int(input('입금액 입력: '))
        koreaBank.doDeposit(myAccount.account_no, m)
        myAccount.printBankInfo()

    elif selectNum == 2:
        m = int(input('출금액 입력: '))
        try:
            koreaBank.doWithdraw(myAccount.account_no, m)
        except bank.LackException as e:
            print(e)
        finally:
            myAccount.printBankInfo()
            
    elif selectNum == 3:
        print('bye')
        break
    
    else:
        print('잘못 입력했습니다. 다시 출력하세요')

0개의 댓글