230417_제로베이스데이터스쿨_파이썬중급문풀_05061~05069

김지태·2023년 4월 18일
0
post-thumbnail

복습 05_053 ~

class Member:
def init(self, i, p):
self.id = i ; self.pw = p

class MemberRepository:
def init(self):
self.members = {}

def addMembers(self, m):
self.members[m.id] = m.pw

def loginMember(self, i, p):
isMember = i in self.members
if isMember and self.members[i] == p:
print(f'{i}: log in 성공')
else:
print(f'{i}: log in fail')

def removeMember(self, i, p):
del self.members[i]

def printMembers(self):
for mk in self.members.key():
print(f'ID: {mk}')
print(f'PW: {self.members[mk]}')

모듈 파일 스마트 티브이

class NormalTv:
def init(self, i = 32, c = 'black', r = 'full-HD'):
self.inch = i
self.color = c
self.resolution = r
self.smartTv = 'off'
self.aiTv = 'off'

def turnOn(self):
print('Tv power on!!')

def turnOff(self):
print('Tv power off!!')

def printTvInfo(self):
print(f'inch: {self.inch}inch')
print(f'color: {self.color}')
print(f'resolution: {self.resolution}')
print(f'smartTv: {self.smartTv}')
print(f'aiTv: {self.aiTv}')

class Tv4k(NormalTv):
def init(self, i, c, r = '4k'):
super().init(i, c, r)

def setSmartTv(self, s):
self.smartTv = s

class Tv8k(NormalTv):
def init(self, i, c, r = '8k'):
super().init(i, c, r)
def setSmartTv(self, s):
self.smartTv = s
def setAiTv(self, a):
self.aiTv = a

===============================================================

ex

import smartTv as st

my4kTv = st.Tv4k('65', 'silver', '4k')
my4kTv.setSmartTv('On')
my4kTv.printTvInfo()
my4kTv.turnOff()

출력 결과

TV power on!!

inch: 65inch

color: silver

resolution: 4k

smartTv: On

aiTv: off

TV power off!!

도서관리 프로그램 05 055

class Book:
def init(self, name, price, isbn):
self.bName = name
self.bPrice = price
self.bIsbn = isbn

class BookRepository:

def init(self):
self.bDic = {}

def registBook(self, b):
self.bDic[b.Isbn] = b

def removeBook(self, isbn):
del self.bDic[isbn]

def printBookInfo(self, isbn):
if isbn in self.bDic:
b = self.bDic[isbn]
print(f'{b.bName}, {b.bPrice}, {b.bIsbn}')

else:
  print('result not exist')
  

05_061 예외처리 2

난수 10개 생성( 소수 ) 소수 아니면 사용자 예외가 발생하도록 프로그램 만들자

난수 발생하면서 그 난수가 소수인 숫자 10개 출력해야함, 하지만 소수가 아니면 사용자 예외 발생해야

모듈 - 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

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

다시 듣기

05_062 예외처리 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('-' 66)
print(f'총 구매 금액: {totalPrice}원')
print('-----------------------미결제 항목------------------')
for g in againCntInput.keys():
print(f'상품: {g}, \t 구매 개수: {againCntInput[g]}')
print('-'
66)

실행 파일 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)

05_063 예외처리 4 - 연습문제

회원가입 프로그램 만들되 입력하지 않은 항목이 있는 경우 에러 메시지를 출력하는 프로그램을 만들자 / 유효성 체크 프로그램

살행파일

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)

모듈파일 - 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_password = p
self.m_address = 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_password: {self.m_password}')
print(f'm_address: {self.m_address}')
print(f'm_phone: {self.m_phone}')

05_064 예외처리 5

은행 계좌 계설 및 입출금 프로그램 만들기

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 += m

def doWithdraw(self, ano, m):
pb = self.accounts[ano]
if pb.totalMoney - m < 0:
raise LackException(pb.totalMoney, m)
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:
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('잘못입력했습니다. 다시 선택하세요.')

05_065 텍스트파일1

모듈 파일 - 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 f:
datas = f.readlines()

return datas

실행 파일 ex

import diary

members = {}

uri = 'C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더'

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

while True:
selectNum = int(input('1. 회원가입 2. 한줄일기쓰기 3. 일기보기 4. 종료'))

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'
  input('오늘 하루 인상 깊은 일을 기록해보자.')
  diary.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 = diary.readDiary(uri, fileName)
  for d in datas:
    print(d, end = '')
  
else:
  print('login fail!!')
  printMembers()
  

elif selectNum == 4 :
print('Bye')
break

05_066 텍스트 파일 02

import time

def getTime():
lt = time.localtime()
time.strftime('%Y-%m-%d %H:%M:%S')
while True:

selectNumber = int(input('1. 입금, \t 2. 출금, \t 3. 종료'))
if selectNumber == 1:
money = int(input('입금액 입력:'))
with open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/money.txt', 'r') as f:
m = f.read()

with open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/money.txt', 'w') as f:
  f.write(str(int(m) + money))
memo = input('입금 내역 입력: ')
with open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/pocketMoneyRegister.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')
  
print('입금 완료!!')
print(f'기존 잔액: {m}')
print(f'입금 후 잔액: {int(m) + money}')


  

elif selectNumber == 2:
money = int(input('출금액 입력:'))
with open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/money.txt', 'r') as f:
m = f.read()

with open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/money.txt', 'w') as f:
  f.write(str(int(m) - money))
memo = input('출금 내역 입력: ')
with open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/pocketMoneyRegister.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')
  
print('출금 완료!!')
print(f'기존 잔액: {m}')
print(f'출금 후 잔액: {int(m) + money}')

elif selectNumber == 3:
print('종료')
break

else:
print('다시 입력하세요.')

05_067 텍스트파일 3

약수

inputNumber = int(input('0보다 큰 정수를 입력: '))
divisor = []
for number in range(1, inputNumber+1):
if inputNumber % number == 0:
divisor.append(number)

if len(divisor) > 0 :
try:
with open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/divisor.txt', 'a') as f:
f.write(f'{inputNumber}의 약수: ')
f.write(f'{divisor}\n')
except Exception as e:
print(e)
else:
print('divisor write complete!!')

소수

inputNumber = int(input('0보다 큰 정수를 입력: '))
prime = []

for number in range(2, (inputNumber + 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:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/prime.txt', 'a') as f:
f.write(f'{inputNumber}까지의 소수: ')
f.write(f'{prime}\n')
except Exception as e:
print(e)
else:
print('prime write complete!!')

05_068 텍스트파일 4

수 입력하면 공약수를 파일에 작성

수 두 개의 공약수

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:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/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보다 큰 정수 입력: '))

maxCommonNum = 0

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

try:
with open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/maxCommonNum.txt', 'a') as f:
f.write(f'{num1}과 {num2}의 최대공약수: {maxCommonNum} \n')
except Exception as e:
print(e)
else:
print('max common factor write complete!!')

05_069 텍스트 파일 05

섬 마을에 과일 생선 야채를 판매하는 배가 특정 주기로 입항한다고 할 때 모든 배가 입항하는 날짜를 텍스트 파일에 기록해보자 / 첫 입항일은 2021년 1월 1일 오전 10시

ship1 = 3
ship2 = 4
ship3 = 5

maxDay = 0

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}')
print(f'maxDay: {maxDay}')

from datetime import datetime
from datetime import timedelta

n = 1
baseTime = datetime(2021, 1, 1, 10, 0, 0)

with open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/arrive.txt', 'a') as f:
f.write(f'2021년 모든 선박 입항일\n')
f.write(f'{baseTime}\n')

nextTime = baseTime + timedelta(days = minDay)
while True:
with open('C:/Users/SAMSUNG/Desktop/제로베이스 데이터스쿨/파이썬 실습용 폴더/arrive.txt', 'a') as f:
f.write(f'{nextTime}\n')

nextTime += timedelta(days = minDay)
if nextTime.year > 2021:
break

profile
데이터 분석가

0개의 댓글