[제로베이스 데이터 취업스쿨] 23.06.14 스터디 노트

김준호·2023년 6월 14일
0
post-thumbnail

파이썬 중급 문제풀이 (예외처리~텍스트)

⭐문제1.⭐ 소수 난수 발생

prime_moduel.py

class NotPrimeNumber(Exception):
    def __init__(self,n):
        super().__init__(f'{n} is not prime number')


class PrimeNumber(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 NotPrimeNumber(number)
    else:
        raise PrimeNumber(number)

main02.py

import random

import prime_moduel as pm

primeNumbers = []

n=0
while n <= 10:

    rn = random.randint(2,1000)
    if rn not in primeNumbers:
        try:
            pm.isPrime(rn)
        except pm.NotPrimeNumber as e:
            print(e)
            continue
        except pm.PrimeNumber as e:
            print(e)
            primeNumbers.append(rn)

    else:
        print(f'{rn} is overlap number')
    n+=1

print(f'primenumbers : {primeNumbers}')
159 is not prime number
293 is prime number
547 is prime number
23 is prime number
243 is not prime number
893 is not prime number
334 is not prime number
324 is not prime number
228 is not prime number
164 is not prime number
903 is not prime number
993 is not prime number
68 is not prime number
757 is prime number
658 is not prime number
270 is not prime number
247 is not prime number
878 is not prime number
302 is not prime number
588 is not prime number
130 is not prime number
743 is prime number
539 is not prime number
832 is not prime number
984 is not prime number
217 is not prime number
7 is prime number
561 is not prime number
843 is not prime number
149 is prime number
161 is not prime number
268 is not prime number
185 is not prime number
161 is not prime number
521 is prime number
211 is prime number
518 is not prime number
80 is not prime number
417 is not prime number
781 is not prime number
49 is not prime number
351 is not prime number
422 is not prime number
742 is not prime number
180 is not prime number
607 is prime number
866 is not prime number
149 is overlap number
primenumbers : [293, 547, 23, 757, 743, 7, 149, 521, 211, 607]

문제2. 영수증 출력 및 예외처리

calculatorPurchase.py

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

def formation(n):
    return format(n,',')
#상품 갯수에 대한 총금액 출력 함수
#몇개 상품을 구매 할 지 모르니 *사용
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'총 구매 금액: {formation(totalPrice)}원')
    print('-------------미결제 항목--------------------------')
    for g in againCntInput.keys():
        print(f'상품: {g}, \t구매 개수: {againCntInput[g]}')
    print('-----------------------------------------------')

main03.py

import calculatorPurchase as cp

g1Num = input('goods1 구매 개수: ')
g2Num = input('goods1 구매 개수: ')
g3Num = input('goods1 구매 개수: ')
g4Num = input('goods1 구매 개수: ')
g5Num = input('goods1 구매 개수: ')

cp.calculator(g1Num,g2Num,g3Num,g4Num,g5Num,)
goods1 구매 개수: 한개
goods1 구매 개수: 3
goods1 구매 개수: 1
goods1 구매 개수: 
goods1 구매 개수: 2
invalid literal for int() with base 10: '한개'
invalid literal for int() with base 10: ''
-----------------------------------------------
총 구매 금액: 5,600원
-------------미결제 항목--------------------------
상품: g1, 	구매 개수: 한개
상품: g4, 	구매 개수: 
-----------------------------------------------

문제3. 회원가입 예외처리

member.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}')

main04.py

import member as mb

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

try:
    mb.checkInputData(m_name, m_mail, m_pw, m_addr, m_phone)
    newMember = mb.RegistMember(m_name, m_mail, m_pw, m_addr, m_phone)
    newMember.printMemberInfo()
except mb.EmptyDataException as e:
    print(e)
이름 입력: ghdrlfehd
메일 입력: ghd@gmail.com
비밀번호 입력: 
주소 입력: korea 
연락처 입력: 010-2020-0230
password is empty
이름 입력: hong gil dong
메일 입력: hong@gmail.com
비밀번호 입력: 1234
주소 입력: korea
연락처 입력: 010-1234-5678
MemberShip complete
m_name : hong gil dong
m_mail : hong@gmail.com
m_pw : 1234
m_addr : korea
m_phone : 010-1234-5678

문제4. 은행계좌, 입출금

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,999999)
            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 += 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}')

main05.py

import bank

koreaBank = bank.Bank()

new_account_name = input('예금주 입력: ')
myAccount = bank.PrivateBank(koreaBank,new_account_name)
myAccount.printBankInfo()

while True:

    selectNum = int(input(f'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('잘못 입력 했습니다. 다시 선택하세요')
예금주 입력: 홀실동
----------------------------------------
account_name :홀실동
account_no :122940
totalMoney :0
----------------------------------------
1.입금 	2.출금 	3.종료: 1
입금액 입력:10000
----------------------------------------
account_name :홀실동
account_no :122940
totalMoney :10000
----------------------------------------
1.입금 	2.출금 	3.종료: 2
출금액 입력:5000
----------------------------------------
account_name :홀실동
account_no :122940
totalMoney :5000
----------------------------------------
1.입금 	2.출금 	3.종료: 2
출금액 입력:7000
잔고 부족!!, 잔액:5000, 출금액: 7000
----------------------------------------
account_name :홀실동
account_no :122940
totalMoney :5000
----------------------------------------
1.입금 	2.출금 	3.종료: 3
Bye

문제5. 일기쓰고 읽기

diary.py

import time

#일기 쓰기 기능
def writeDiary(u, f, d):
    lt = time.localtime()
    timeStr = time.strftime('%Y-%m-%d %I:%M:%S %p', lt)

    #모듈이기 때문에 경로를 받아주어야 한다.
    filePath = u+f
    with open(filePath,'a') as f:
        f.write(f'[{timeStr}] {d}\n')

#일기 읽기 기능
def readDiary(u, f):
    # 모듈이기 때문에 경로를 받아주어야 한다.
    filePath = u + f
    datas = []
    with open(filePath, 'r') as r:
        datas = r.readlines()

        #읽고 반환해줘야 출력에 보임
        return datas

main01.py

import diary as dy

members = {}
uri = 'C:/pythonTxt/'

def printMembers():
    for m in members.keys():
        print(f'ID : {m}\t PW:{members[m]}')

while True:
    selectNum = int(input('1.회원가입 \t2.한줄일기쓰기 \t3.일기보기 \t4.종료'))
    if selectNum == 1:
        mId = input('input ID:')
        mPw = input('input PW:')
        members[mId] = mPw
        printMembers()
    elif selectNum == 2:
        mId = input('input ID:')
        mPw = input('input PW:')

        if mId in members and members[mId] == mPw:
            print('login success')
            fileName = 'myDiary_'+mId + 'txt'
            data = input('오늘하루 인상 깊은 일: ')
            dy.writeDiary(uri,fileName, data)

        else:
            print('login Fail')
            printMembers()


    elif selectNum == 3:
        mId = input('input ID:')
        mPw = input('input PW:')

        if mId in members and members[mId] == mPw:
            print('login success')
            fileName = 'myDiary_' + mId + 'txt'
            datas = dy.readDiary(uri, fileName)
            for d in datas:
                print(d,end='')
        else:
            print('login Fail')
            printMembers()

    elif selectNum == 4:
        print('Bye')
        break
1.회원가입 	2.한줄일기쓰기 	3.일기보기 	4.종료1
input ID:chanho
input PW:1234
ID : chanho	 PW:1234
1.회원가입 	2.한줄일기쓰기 	3.일기보기 	4.종료1
input ID:son
input PW:0000
ID : chanho	 PW:1234
ID : son	 PW:0000
1.회원가입 	2.한줄일기쓰기 	3.일기보기 	4.종료2
input ID:chanho
input PW:1234
login success
오늘하루 인상 깊은 일: python
1.회원가입 	2.한줄일기쓰기 	3.일기보기 	4.종료3
input ID:chanho
input PW:1234
login success
[2023-06-14 12:38:30 AM] python
[2023-06-14 12:56:40 AM] python
1.회원가입 	2.한줄일기쓰기 	3.일기보기 	4.종료4
Bye

문제6. 가게부 작성

#가게부는 잔액관리를 하기 위해 작성한다.
#잔액만 관리되는 텍스트 파일, 가게부 총 2개 텍스트 파일을 만들어서 실행 해야 한다.

import time

def getTime():
    lt = time.localtime()
    st = time.strftime('%Y-%m-%d %H:%M:%S %p',lt)
    return st

while True:
    selectNum = int(input('1.입금 \t2.출금 \t3.종료'))
    
    if selectNum == 1:
        money = int(input('입금액 입력:'))
        #잔액을 읽어 드릴 텍스트 파일 먼저 만들고 잔액을 읽는다.
        #파일을 먼저 만들고 읽는 이유는 r기능은 파일이 없으면 에러가 나온다.
        with open('C:/pythonTxt/bank/money.txt','r') as f:
            m = f.read()

        with open('C:/pythonTxt/bank/money.txt','w') as f:
            f.write(str(int(m) + money))

        memo = input('입금 내역 입력:')
        with open('C:/pythonTxt/bank/poketMoneyRegister.txt','a') as f:
            f.write('------------------------------------------------\n')
            f.write(f'[{getTime()}]\n')
            f.write(f'[입금]{memo} : {str(money)}원\n')
            f.write(f'[잔액] : {str(int(m)+money)}원\n')
            f.write('------------------------------------------------\n')
            
        print('입금 완료!!')
        print(f'입금 후 잔액: {int(m)+money}원')


    elif selectNum == 2:
        money = int(input('출금액 입력:'))
        with open('C:/pythonTxt/bank/money.txt', 'r') as f:
            m = f.read()

        with open('C:/pythonTxt/bank/money.txt', 'w') as f:
            f.write(str(int(m) - money))

        memo = input('출금 내역 입력:')
        with open('C:/pythonTxt/bank/poketMoneyRegister.txt', 'a') as f:
            f.write('------------------------------------------------\n')
            f.write(f'[{getTime()}]\n')
            f.write(f'[출금]{memo} : {str(money)}원\n')
            f.write(f'[잔액] : {str(int(m) - money)}원\n')
            f.write('------------------------------------------------\n')

        print('출금 완료!!')
        print(f'출금 후 잔액: {int(m) - money}원')


    elif selectNum == 3:
        print('BYE~')
        break
    else:
        print('다시 입력 하세요')
1.입금 	2.출금 	3.종료1
입금액 입력:3000000
입금 내역 입력:월급
입금 완료!!
입금 후 잔액: 3000000원
1.입금 	2.출금 	3.종료2
출금액 입력:1000000
출금 내역 입력:TV구맨
출금 완료!!
출금 후 잔액: 2000000원
1.입금 	2.출금 	3.종료2
출금액 입력:500000
출금 내역 입력:게임기 구매
출금 완료!!
출금 후 잔액: 1500000원
1.입금 	2.출금 	3.종료3
BYE~

문제7. 약수,소수 텍스트파일에 쓰기

약수

#약수

inputNum1 = int(input('0보다 큰 정수 입력: '))

divisor = []
for number in range(1,(inputNum1+1)):
    if inputNum1 % number == 0:
        divisor.append(number)

if len(divisor) > 0:
    try:
        with open('C:/pythonTxt/divisor.txt','a') as f:
            f.write(f'{inputNum1}의 약수 : ')
            f.write(f'{divisor}\n')
    except Exception as e:
        print(e)
    else:
        print('divisor write Complete')

소수

#소수
inputNum = int(input('2보다 큰 정수 입력: '))
prime = []

for number in range(2,(inputNum+1)):
    flag = True
    for n in range(2,number):
        if number % n == 0:
            flag = False
            break

    if flag:
        prime.append(number)

if len(prime) > 0:
    try:
        with open('C:/pythonTxt/prime.txt','a') as f:
            f.write(f'{inputNum}까지의 소수 : ')
            f.write(f'{prime}\n')
    except Exception as e:
        print(e)
    else:
        print('prime write Complete')

문제8. 공약수, 최대공약수 텍스트파일에 쓰기

num1 = int(input('1보다 큰 정수 입력:'))
num2 = int(input('1보다 큰 정수 입력:'))

common = []
for i in range(1, (num1+1)):
    if num1 % i == 0 and num2 % i == 0:
        common.append(i)

if len(common) > 0:
    try:
        with open('C:/pythonTxt/common.txt','a') as f:
            f.write(f'{num1}과 {num2}의 공약수')
            f.write(f'{common}\n')
    except Exception as e:
        print(e)

    else:
        print('common factor write complete')

#두 수의 최대공약수
num1 = int(input('1보다 큰 정수 입력:'))
num2 = int(input('1보다 큰 정수 입력:'))

maxComNum = 0
for i in range(1, (num1+1)):
    if num1 % i == 0 and num2 % i == 0:
        maxComNum = i


try:
    with open('C:/pythonTxt/maxComNum.txt','a') as f:
        f.write(f'{num1}과 {num2}의 최대공약수: {maxComNum}\n')
except Exception as e:
    print(e)

else:
    print('maxcommon factor write complete')

문제8. 입항 날짜 구하기(3가지 숫자 최소공배수)

#배들의 주기
ship1 = 3
ship2 = 4
ship3 = 5
maxDay = 0

#세개 수의 최소공배수--> 2개 먼저 구한 값이랑 세버째 값이랑

for i in range(1,(ship1 +1)):
    if ship1 % i == 0 and ship2 % i ==0:
        maxDay = i
#최소공배수 공식 = 두수 곱을 최대공약수로 나눈값
minDay = (ship1 * ship2 )//maxDay

newDay = minDay
for i in range(1, newDay+1):
    if newDay % i ==0 and ship3 % i == 0:
        maxDay = i

minDay = newDay * ship3 // maxDay

print(f'minDay : {minDay}')



#위에서 구한 최소공배수로 주기를 알았고 주기마다 날짜를 텍스트 파일에 쓰기

from datetime import datetime
from  datetime import timedelta

n = 1
#datetime 함수는 기준일을 정할 수 있다.
baseTime = datetime(2021, 1, 1, 10, 0, 0)

#기준일 작성
with open('C:/pythonTxt/arrive.txt','a') as f:
    f.write(f'2021년 모든 선박 입항일\n')
    f.write(f'{baseTime}\n')

#다음 주기 날짜 작성
#timedelta함수는 지정 날부터 숫자를 입력해서 날짜를 구해 준다.
nextTime = baseTime + timedelta(days=minDay)
while True:

    with open('C:/pythonTxt/arrive.txt','a')as f:
        f.write(f'{nextTime}\n')

    nextTime = nextTime + timedelta(days=minDay)

    if nextTime.year > 2021:
        break
profile
취업공부

0개의 댓글