사용자가 입력한 숫자를 이용해서 산술연산 결과를 출력하는 모듈을 만들되,
예상하는 예외에 대한 예외처리 코드를 작성해보자
#module 파일의 calculator 모듈
class Calculator :
def __init__(self,n1,n2):
try:
self.num1 = float(n1)
self.num2 = float(n2)
except :
print('숫자를 입력해주세요.')
def add(self):
result = self.num1 + self.num2
print(f'{self.num1} + {self.num2} = {result}')
def sub(self):
result = self.num1 - self.num2
print(f'{self.num1} - {self.num2} = {result}')
def div(self):
try :
result = self.num1 / self.num2
except Exception as e :
print('0으로 나눌 수 없습니다')
print(e)
else :
print(f'{self.num1} / {self.num2} = {result}')
def mul(self):
result = self.num1 * self.num2
print(f'{self.num1} * {self.num2} = {result}')
from module import calculator as c
num1 = input('첫번째 피연산자 입력 : ')
num2 = input('두번째 피연산자 입력 : ')
i = c.Calculator(num1,num2)
i.add()
i.sub()
i.div()
i.mul()
문제는 모듈을 만드는 것이었지만
클래스 복습 겸 클래스로 짜보았다.
div의 float division by zero error를 잡기위해 따로 try 구문을 넣어주었고,
init에 try로 float 형변환 시켰다.
1부터 1000까지의 소수인 난수 10개를 생성하되,
소수가 아니면 사용자 예외가 발생하도록 프로그램을 만들어보자
class Not_Prime_Exception(Exception) :
def __init__(self,n):
super().__init__(f'{n} is not prime number')
class Prime_Exception(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 Not_Prime_Exception(number)
else :
raise Prime_Exception(number)
import random
from module import prime as p
prime_numbers = []
n = 0
while n < 10 :
rn = random.randint(2,1000)
if rn not in prime_numbers:
try :
p.isprime(rn)
except p.Not_Prime_Exception as e :
print(e)
except p.Prime_Exception as e :
print(e)
prime_numbers.append(rn)
n += 1
else :
print(f'{rn} is overlap number')
continue
print(f'prime numbers : {prime_numbers}')
강사님의 경우 소수일경우 발생시킬 사용자예외클래스와
소수가 아닐 경우 발생시킬 사용자 예외 클래스
두가지를 코딩해두고
소수인지 아닌지 구별하는 모듈을 만든 후에
실행파일에서 p.isprime(rn)에 except을 두번 넣으셨다.
즉, 소수가 아닐 때는 Prime_Exception가 발생
소수일 때는 Not_Prime_Exception가 발생함과 동시에 리스트에 수를 담는다.
나는 아래처럼 prime_exception을 짜지 않고
소수가 아닐경우에만 Not_Prime_Exception 발생시킨 후
소수일 경우 else로 바로 리스트에 append시켰다.
class Not_Prime_Exception(Exception) :
def __init__(self,n):
super().__init__(f'{n} is not prime number')
# class Prime_Exception(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 Not_Prime_Exception(number)
break
# else :
# raise Prime_Exception(number)
import random
from module import prime as p
prime_numbers = []
n = 0
while n < 10 :
rn = random.randint(2,1000)
if rn not in prime_numbers:
try :
p.isprime(rn)
except p.Not_Prime_Exception as e :
print(e)
# except p.Prime_Exception as e :
else :
# print(e)
prime_numbers.append(rn)
n += 1
else :
print(f'{rn} is overlap number')
continue
다만, 모듈의 isprime함수에서 flase일 경우에만 실행 종료되도록 break 위치를 조정했다.
상품구매에 따른 총 구매금액을 출력하되,
다음과 같이 개수가 잘못 입력된 경우 별도로 출력하도록 프로그램을 만들어보자
g1 = 1500 ; g2 = 2000 ; g3 = 3000 ; g4 = 500 ; g5 = 5000
def calculator(*g) :
g_dic = {}
again_dic = {}
for idx,cnt in enumerate(g):
try :
g_dic[f'g{idx+1}'] = int(cnt)
except Exception as e :
print(e)
again_dic[f'g{idx+1}'] = cnt
total_price = 0
for i in g_dic.keys() :
total_price += g_dic[i] * globals()[f'{i}']
#전역변수의 변수명을 포멧으로 불러옴
print('-'*61)
print(f'총 구매금액 : {format(total_price,',')}원')
print('-'*61)
if len(again_dic) != 0 :
for key, value in again_dic.items() :
print(f'상품 : {key},\t\t구매개수 : {value}')
print('-'*61)
from module import price as p
good1 = input('good1 구매 갯수 : ')
good2 = input('good2 구매 갯수 : ')
good3 = input('good3 구매 갯수 : ')
good4 = input('good4 구매 갯수 : ')
good5 = input('good5 구매 갯수 : ')
p.calculator(good1,good2,good3,good4,good5)
모듈에 상품별 가격을 변수로 설정해준뒤 계산함수를 만들어준다.
사용자가 숫자로 입력될 경우 g_dic 딕셔너리에 상품명과 구매갯수를 key와 value로 넣어주고
아닐경우 예외처리로 에러를 출력해준 뒤
별로로 again_dic 딕셔너리에 상품명과 입력값을 key와 value로 넣어준다.
가장 어려웠던 부분은 total_price였는데,
이때 globals 함수를 사용했다.
전역변수의 변수명을 포맷값으로 불러올 수 있다.
for i in g_dic.keys() :
total_price += g_dic[i] * globals()[f'{i}']
g_dic의 딕셔너리에는 g1 g2 의 key값과 사용자가 입력한 상품 개수가 value로 입력되어있는데,
전역변수로 g1 = 1500 g2 = 2000 처럼 미리 변수를 설정해두었기 때문에
해당 변수값이 들어오는 것이다.
만약 전역변수명을 g1_price로 했다면,
globals()[f'{i}_price']
로 입력했을 시 동일하게 값이 들어오겠다.
회원가입 프로그램을 만들되 입력하지 않은 항목이 있는 경우 에러메세지를 출력
class Empty(Exception) :
def __init__(self,m):
super().__init__(f'{m} is empty')
def check_input_data(n,m,p,a,ph) :
if n == '':
raise Empty('name')
if m == '':
raise Empty('mail')
if p == '':
raise Empty('pw')
if a == '':
raise Empty('address')
if ph == '':
raise Empty('phone')
class membership :
def __init__(self,n,m,p,a,ph):
self.name = n
self.mail = m
self.pw = p
self.address = a
self.phone = ph
self.list = {}
def completed_print(self):
self.list['m_name'] = self.name
self.list['m_mail'] = self.mail
self.list['m_pw'] = self.pw
self.list['m_address'] = self.address
self.list['m_phone'] = self.phone
print('Merbership completed')
for key, value in self.list.items() :
print(f'{key} : {value}')
from module import join as j
name = input('이름 입력 : ')
mail = input('메일 입력 : ')
pw = input('비밀번호 입력 : ')
address = input('주소 입력 : ')
phone = input('핸드폰번호 입력 : ')
try:
j.check_input_data(name,mail,pw,address,phone)
j.membership(name, mail, pw, address, phone).completed_print()
except j.Empty as e :
print(e)
입출금 class를 만들고 잔액보다 출금액이 클경우 사용자 예외처리가 발생하는 프로그램을 만들어보자
class Draw_error(Exception) :
def __init__(self):
super().__init__('잔고부족')
import random
class Bank :
def __init__(self,n):
self.name = n
self.account_no = random.randint(4000,5000)
self.total_money = 0
self.print_info()
while True :
select_num = int(input('1.입금\t2.출금\t3.종료 : '))
if select_num == 1 :
deposit_money = int(input('입금액 입력 : '))
self.deposit(deposit_money)
elif select_num == 2 :
try :
draw_money = int(input('출금액 입력 : '))
self.draw(draw_money)
except Draw_error as e:
print(e,end='')
print(f', 잔액 : {self.total_money}, 출금액 : {draw_money}')
elif select_num == 3 :
print('Bye')
break
else :
print('잘못 입력 하셨습니다.')
def deposit(self,deposit_money):
self.total_money += deposit_money
self.print_info()
def draw(self,draw_money):
if self.total_money - draw_money < 0 :
raise Draw_error
else :
self.total_money -= draw_money
self.print_info()
def print_info(self):
print('-' * 50)
print(f'account_name : {self.name}')
print(f'account_no : {self.account_no}')
print(f'total_money : {self.total_money}원')
print('-' * 50)
user_name = input('통장개설을 위한 예금주 입력 : ')
Bank(user_name)
오늘의 실수 super()의 ()를 누락하여 Exception 클래스를 부모클래스로 받아오는데 실패 -> error
학습질문방에 질문을 올렸는데, 동기가 chatGPT로 도움을 주었다
(바로 peo 구독함..)