📌 파이썬 연습문제 [예외]
📋예외처리를 이용한 산술연산 프로그램
def add(n1, n2):
try:
n1 = float(n1)
n2 = float(n2)
print(f'{n1} + {n2} : {n1 + n2}')
except:
print(f'숫자만 입력하세요')
def sub(n1, n2):
try:
n1 = float(n1)
n2 = float(n2)
print(f'{n1} - {n2} : {n1 - n2}')
except:
print(f'숫자만 입력하세요')
def mul(n1, n2):
try:
n1 = float(n1)
n2 = float(n2)
print(f'{n1} * {n2} : {n1 * n2}')
except:
print(f'숫자만 입력하세요')
def div(n1, n2):
try:
n1 = float(n1)
n2 = float(n2)
print(f'{n1} / {n2} : {n1 / n2}')
except ZeroDivisionError:
print(f'0으로 나눌 수 없습니다.')
except:
print(f'숫자만 입력하세요')
def mod(n1, n2):
try:
n1 = float(n1)
n2 = float(n2)
if n2 == 0:
print(f'0으로 나눌 수 없습니다')
return
else:
print(f'{n1} % {n2} : {n1 % n2}')
except:
print(f'숫자만 입력하세요')
def flo(n1, n2):
try:
n1 = float(n1)
n2 = float(n2)
if n2 == 0:
print(f'0으로 나눌 수 없습니다')
return
else:
print(f'{n1} // {n2} : {n1 // n2}')
except:
print(f'숫자만 입력하세요')
def exp(n1, n2):
try:
n1 = float(n1)
n2 = float(n2)
print(f'{n1} ** {n2} : {n1 ** n2}')
except:
print(f'숫자만 입력하세요')
---------------------------------------------------
💡main
print('-' * 30)
while True:
try:
operate = int(input('1.덧셈 \t 2.뺄셈 \t 3.곱셈 \t 4.나눗셈 \t 5.나머지 \t 6.몫 \t 7.제곱승 \t 8.종료 : '))
except:
print('다시 입력하세요.')
continue
if operate == 8:
print('Bye~')
break
n1 = input('첫 번째 숫자 입력 : ')
n2 = input('두 번째 숫자 입력 : ')
if operate == 1:
add(n1, n2)
elif operate == 2:
sub(n1, n2)
elif operate == 3:
mul(n1, n2)
elif operate == 4:
div(n1, n2)
elif operate == 5:
mod(n1, n2)
elif operate == 6:
flo(n1, n2)
elif operate == 7:
exp(n1, n2)
else:
print('다시 입력해주세요')
📋 1부터 1000까지의 소수인 난수 10개를 생성하되,소수가 아니면 예외가 발생
import random
💡예외 NotPrimeException
class NotPrimeException(Exception):
def __init__(self, n):
super().__init__(f'{n} is not prime number.')
💡예외 PrimeException
class PrimeException(Exception):
def __init__(self, n):
super().__init__(f'{n} is prime number.')
---------------------------------------------------
💡main
def isPrime(number):
isPrime = True
for i in range(2, number + 1):
if number % i == 0 and i != number:
isPrime = False
if isPrime:
raise PrimeException(number)
else:
raise NotPrimeException(number)
rands = random.sample(range(1, 1000), 10)
primes = []
for prime in rands:
try:
isPrime(prime)
except NotPrimeException as e:
print(e)
continue
except PrimeException as e:
print(e)
primes.append(prime)
print(f'Random Number : {rands}')
print(f'Prime Number : {primes}')
📋총 구매 내역 프로그램
items = {'딸기': 2000, '바나나': 1500, '귤': 500, '메론': 3000, '사과': 1300}
errors = {}
total = 0
cnt = 0
for key in items.keys():
try:
cnt = input(f'{key} 구매 개수 : ')
total += (int(cnt) * items[key])
except Exception as e:
errors[key] = cnt
continue
print('-' * 30)
print(f'총 구매 금액 : {total}원')
print('-' * 12, '미결제 항목', '-' * 12)
for k in errors:
print(f'상품 : {k} | 구매 개수 : {errors[k]}')
📋 회원가입 프로그램
💡예외 DataEmptyException
class DataEmptyException(Exception):
def __init__(self, val):
super().__init__(f'{val} is empty')
💡클래스 Member
class Member:
def __init__(self, name, mail, pw, address, phone):
self.name = name
self.mail = mail
self.pw = pw
self.address = address
self.phone = phone
print('Membership completed!!')
def printMemberInfo(self):
print(f'name : {self.name}')
print(f'mail : {self.mail}')
print(f'pw : {self.pw}')
print(f'address : {self.address}')
print(f'phone : {self.phone}')
---------------------------------------------------
💡main
def registerMember():
name = input('이름 입력 : ')
mail = input('메일 입력 : ')
pw = input('비밀번호 입력 : ')
address = input('주소 입력 : ')
phone = input('연락처 입력 : ')
if name == '':
raise DataEmptyException('name')
if mail == '':
raise DataEmptyException('mail')
if pw == '':
raise DataEmptyException('pw')
if address == '':
raise DataEmptyException('address')
if phone == '':
raise DataEmptyException('phone')
mem = Member(name, mail, pw, address, phone)
mem.printMemberInfo()
try:
registerMember()
except DataEmptyException as e:
print(e)
📋 은행 계좌 프로그램
import random
💡예외 BankException
class BankException(Exception):
def __init__(self, balance, withdraw):
super().__init__(f'잔고부족 ! 잔액 : {balance} 출금액 : {withdraw}')
💡클래스 Account
class Account:
def __init__(self, name, bank):
self.name = name
self.bank = bank
self.totalMoney = 0
while True:
self.no = random.randint(1000, 9999)
if bank.isAccount(self.no):
continue
else:
break
self.printAccount()
def printAccount(self):
print('-' * 30)
print(f'account_name : {self.name}')
print(f'account_no : {self.no}')
print(f'totalMoney : {self.totalMoney}원')
print('-' * 30)
💡클래스 Bank
class Bank:
def __init__(self):
self.accounts = {}
def addAccount(self, account):
self.accounts[account.no] = account
def isAccount(self, no):
if no in self.accounts:
return True
else:
return False
def deposit(self, no, money):
if no in self.accounts:
account = self.accounts[no]
account.totalMoney += money
else:
print('존재하지 않는 계좌입니다')
def withdraw(self, no, money):
if no in self.accounts:
account = self.accounts[no]
if account.totalMoney - money > 0:
account.totalMoney -= money
else:
raise BankException(account.totalMoney, money)
else:
print('존재하지 않는 계좌입니다')
---------------------------------------------------
💡main
bank = Bank()
name = input('통장 계설을 위한 예금주 입력 : ')
account = Account(name, bank)
bank.addAccount(account)
while True:
num = int(input('1. 입금, 2. 출금, 3. 종료 : '))
if num == 1:
money = int(input('입금액 입력 : '))
bank.deposit(account.no, money)
account.printAccount()
if num == 2:
try:
money = int(input('출금액 입력 : '))
bank.withdraw(account.no, money)
account.printAccount()
except BankException as e:
print(e)
finally:
account.printAccount()
if num == 3:
print('종료')
break