3️⃣ 파이썬 중급 문제풀이
40. 함수 (01)
def add(n1, n2):
return n1 + n2ㅂ
def sub(n1, n2):
return n1 - n2
def mul(n1, n2):
return n1 * n2
def div(n1, n2):
return n1 / n2
def mod(n1, n2):
return n1 % n2
def flo(n1, n2):
return n1 // n2
def exp(n1, n2):
return n1 ** n2
while True:
print('-' * 60)
selectNum = int(input('1.덧셈, 2.뺄셈, 3.곱셈, 4.나눗셈, 5.나머지, 6.몫, 7.제곱승, 8.종료'))
if selectNum == 8:
print('Bye~')
break
num1 = float(input('첫 번째 숫자 입력: '))
num2 = float(input('두 번째 숫자 입력: '))
if selectNum == 1:
print(f'{num1} + {num2} = {add(num1, num2)}')
elif selectNum == 2:
print(f'{num1} - {num2} = {sub(num1, num2)}')
elif selectNum == 3:
print(f'{num1} * {num2} = {mul(num1, num2)}')
elif selectNum == 4:
print(f'{num1} / {num2} = {div(num1, num2)}')
elif selectNum == 5:
print(f'{num1} % {num2} = {mod(num1, num2)}')
elif selectNum == 6:
print(f'{num1} // {num2} = {flo(num1, num2)}')
elif selectNum == 7:
print(f'{num1} ** {num2} = {exp(num1, num2)}')
else:
print('잘못 입력했습니다. 다시 입력하세요.')
print('-' * 60)
41. 함수 (02) - 거리, 속력, 시간 계산
def getDistance(s, h, m):
distance = s * (h + m/60)
return distance
def getTime(s, d):
time = d / s
print(f'time: {time}')
h = int(time)
m = int((time - h) * 100 * 60 / 100)
return [h, m]
print('-' * 60)
s = float(input('속도(km/h) 입력: '))
h = float(input('시간(h) 입력: '))
m = float(input('시간(m) 입력: '))
d = getDistance(s, h, m)
print(f'{s}(km/h)속도로 {h}(h)시간 {m}분 동안 이동한 거리: {d}(km)')
print('-' * 60)
print('-' * 60)
s = float(input('속도(km/h) 입력: '))
d = float(input('거리(km) 입력: '))
t = getTime(s, d)
print(f'{s}(km/h)속도로 {d}(km) 이동한 시간: {t[0]}(h)시간 {t[1]}(m)분')
print('-' * 60)
42. 함수 (03) - 요금 계산
childPrice = 18000
infantPrice = 25000
adultPrice = 50000
specialDC = 50
def formatedNumber(n):
return format(n, ',')
def printAirPlaneReceipt(c1, c2, i1, i2, a1, a2):
cp = c1 * childPrice
cp_dc = int(c2 * childPrice * 0.5)
print(f'유아 {c1}명 요금: {formatedNumber(cp)}원')
print(f'유아 할인 대상 {c2}명 요금: {formatedNumber(cp_dc)}원')
ip = i1 * infantPrice
ip_dc = int(i2 * infantPrice * 0.5)
print(f'소아 {i1}명 요금: {formatedNumber(ip)}원')
print(f'소아 할인 대상 {i2}명 요금: {formatedNumber(ip_dc)}원')
ap = a1 * adultPrice
ap_dc = int(a2 * adultPrice * 0.5)
print(f'성인 {a1}명 요금: {formatedNumber(ap)}원')
print(f'성인 할인 대상 {a2}명 요금: {formatedNumber(ap_dc)}원')
print(f'Total: {formatedNumber(c1 + c2 + i1 + i2 + a1 + a2)}명')
print(f'TotalPrice: {formatedNumber(cp + cp_dc + ip + ip_dc + ap + ap_dc)}원')
childCnt = int(input('유아 입력: '))
specialDCChildCnt = int(input('할인 대상 유아 입력: '))
infantCnt = int(input('소아 입력: '))
specialDCinfantCnt = int(input('할인 대상 소아 입력: '))
adultCnt = int(input('성인 입력: '))
specialDCAdultCnt = int(input('할인 대상 성인 입력: '))
printAirPlaneReceipt(childCnt, specialDCChildCnt, infantCnt, specialDCinfantCnt, adultCnt, specialDCAdultCnt)
43. 함수 (04) - 단리 / 월복리
def formatedNumber(n):
return format(n, ',')
def singleRateCalculator(m, t, r):
totalMoney = 0
totalRateMoney = 0
for i in range(t):
totalRateMoney += m * (r * 0.01)
totalMoney = m + totalRateMoney
return int(totalMoney)
def multiRateCalculator(m, t, r):
t = t * 12
rpm = (r / 12) * 0.01
totalMoney = m
for i in range(t):
totalMoney = totalMoney + (totalMoney * rpm)
return int(totalMoney)
money = int(input('예치금: '))
term = int(input('기간(년): '))
rate = int(input('연 이율(%): '))
print('[단리 계산기]')
print(f'{term}년 후 총 수령액 : {formatedNumber(singleRateCalculator(money, term, rate))}원')
print('[복리 계산기]')
print(f'{term}년 후 총 수령액 : {formatedNumber(multiRateCalculator(money, term, rate))}원')
44. 함수 (05) - 등차 수열
def sequenceCal(n1, d, n):
valueN = 0; sumN = 0;
i = 1
while i <= n:
if i == 1:
valueN = n1
sumN += valueN
print(f'{i}번째 항의 값: {valueN}')
print(f'{i}번째 항까지의 값: {sumN}')
i += 1
continue
valueN += d
sumN += valueN
print(f'{i}번째 항의 값: {valueN}')
print(f'{i}번째 항까지의 값: {sumN}')
i += 1
inputN1 = int(input('a1 입력: '))
inputD = int(input('공차 입력: '))
inputN = int(input('n 입력: '))
sequenceCal(inputN1, inputD, inputN)
45. 함수 (06) - 등비 수열
def sequenceCal (n1, r, n):
valueN = 0; sumN = 0
i = 1
while i <= n:
if i == 1:
valueN = n1
sumN = valueN
print(f'{i}번째 항의 값: {valueN}')
print(f'{i}번째 항까지의 값: {sumN}')
i += 1
continue
valueN *= r
sumN *= valueN
print(f'{i}번째 항의 값: {valueN}')
print(f'{i}번째 항까지의 값: {sumN}')
i += 1
inputN1 = int(input('a1 입력: '))
inputR = int(input('공비 입력: '))
inputN = int(input('n 입력: '))
sequenceCal(inputN1, inputR, inputN)
46. 모듈 (01) - 시험 합불 판단
def exampleResult(s1, s2, s3, s4, s5):
passAvgScore = 60;
limitScore = 40
def getTotal():
totalScore = s1 + s2 + s3 + s4 + s5
print(f'총점: {totalScore}')
return totalScore
def getAverage():
avg = getTotal() / 5
print(f'평균: {avg}')
return avg
def printPassOrFail():
print(f'{s1}: Pass') if s1 >= limitScore else print(f'{s1}: Fail')
print(f'{s2}: Pass') if s1 >= limitScore else print(f'{s2}: Fail')
print(f'{s3}: Pass') if s1 >= limitScore else print(f'{s3}: Fail')
print(f'{s4}: Pass') if s1 >= limitScore else print(f'{s4}: Fail')
print(f'{s5}: Pass') if s1 >= limitScore else print(f'{s5}: Fail')
def printFinalPassOrFail():
if getAverage() >= passAvgScore:
if s1 >= limitScore and s2 >= limitScore and s3 >= limitScore and s4 >= limitScore and s5 >= limitScore:
print('Final Pass!!')
else:
print('Final Fail!!')
else:
print('Final Fail!!')
getAverage()
printPassOrFail()
printFinalPassOrFail()
import passOrFail as pf
if __name__ == '__main__':
sub1 = int(input('과목1 점수 입력: '))
sub2 = int(input('과목2 점수 입력: '))
sub3 = int(input('과목3 점수 입력: '))
sub4 = int(input('과목4 점수 입력: '))
sub5 = int(input('과목5 점수 입력: '))
pf.exampleResult(sub1, sub2, sub3, sub4, sub5)
47. 모듈 (02) - 상품 개수에 따른 할인율 결정 모듈
def calculatorTotalPrice(gs):
if len(gs) <= 0:
print('구매 상품이 없습니다.')
return
rate = 25
totalPrice = 0
rates = {1:5, 2:10, 3:15, 4:20}
if len(gs) in rates:
rate = rates[len(gs)]
for g in gs:
totalPrice += g * (1 - rate * 0.01)
return [rate, int(totalPrice)]
def formatedNumber(n):
return format(n, ',')
import discount as dc
if __name__ == '__main__':
flag = True
gs = []
while flag:
selecNumber = int(input('상품을 구매 하시겠어요? 1.구매 2.종료'))
if selecNumber == 1:
goods_price = int(input('상품 가격 입력: '))
gs.append(goods_price)
elif selecNumber == 2:
result = dc.calculatorTotalPrice(gs)
flag = False
print(f'할인율: {result[0]}%')
print(f'합계: {dc.formatedNumber(result[1])}원')
48. 모듈 (03) - 로또 모듈
import random
import random
userNums = []
randNums = []
collNums = []
randBonNum = 0
def setUserNum(ns):
global userNums
userNums = ns
return userNums
def setRandNums():
global randNums
randNums = random.sample(range(1, 46), 6)
return randNums
def setBonNum():
global randBonNum
while True:
randBonNum = random.randint(1,45)
if randBonNum not in randNums:
break
return randBonNum
def lottoResult():
global userNums
global randNums
global collNums
collNums = []
for un in userNums:
if un in randNums:
collNums.append(un)
if len(collNums) == 6:
print('1등 당첨')
print(f'번호: {collNums}')
elif (len(collNums) == 5) and (randBonNum in userNums):
print('2등 당첨')
print(f'번호: {collNums}, 보너스 번호: {randBonNum}')
elif len(collNums) == 5:
print('3등 당첨')
print(f'번호: {collNums}')
elif len(collNums) == 4:
print('4등 당첨')
print(f'번호: {collNums}')
elif len(collNums) == 3:
print('5등 당첨')
print(f'번호: {collNums}')
else:
print('아쉽습니다. 다음 기회에~')
print(f'당첨 번호: {randNums}')
print(f'보너스 번호: {randBonNum}')
print(f'선택 번호: {userNums}')
print(f'일치 번호: {collNums}')
def startLotto():
n1 = int(input('번호(1~45) 입력: '))
n2 = int(input('번호(1~45) 입력: '))
n3 = int(input('번호(1~45) 입력: '))
n4 = int(input('번호(1~45) 입력: '))
n5 = int(input('번호(1~45) 입력: '))
n6 = int(input('번호(1~45) 입력: '))
selectNums = [n1, n2, n3, n4, n5, n6]
setUserNum(selectNums)
setRandNums()
setBonNum()
lottoResult()
import lotto as lt
lt.startLotto()
49. 모듈 (04) - 순열(P) 모듈
def getPermutationCnt(n, r, logPrint = True):
result = 1
for n in range(n, (n-r), -1):
if logPrint: print('n: {}'.format(n))
result = result * n
return result
from itertools import permutations
def getPermutations(ns, r):
pList = list(permutations(ns, r))
print(f'{len(ns)}P{r} 개수: {len(pList)}')
for n in permutations(ns, r):
print(n, end='')
import permutation as pt
numN = int(input('numN 입력: '))
numR = int(input('numR 입력: '))
listVar = [1,2,3,4,5,6,7,8]
rVar = 3
pt.getPermutations(listVar, rVar)
50. 모듈 (05) - 조합(C) 모듈
def getCombinationCnt(n, r, logPrint = True):
resultP = 1
resultR = 1
resultC = 1
for n in range(n, (n-r), -1):
resultP = resultP * n
if logPrint: print(f'resultP: {resultP}')
for n in range(r, 0, -1):
resultR = resultR * n
if logPrint: print(f'resultR: {resultR}')
resultC = int(resultP / resultR)
if logPrint: print(f'resultC: {resultC}')
return resultC
from itertools import combinations
def getCombinations(ns, r):
clist = list(combinations(ns, r))
print(f'{len(ns)}C{r}: {len(clist)}')
for n in combinations(ns, r):
print(n, end='')
import combination as ct
numN = int(input('numN 입력: '))
numR = int(input('numR 입력: '))
print(f'{numN}C{numR}: {ct.getCombinationCnt(numN, numR, logPrint=False)}')
listVar = [1,2,3,4,5,6,7,8]
rVar = 3
ct.getCombinations(listVar, rVar)
51. 모듈 (06) - 공과금 총액 및 비율 구하기 모듈
income = 0
waterPrice = 0; electricPrice = 0; gasPrice = 0
def setIncome(ic):
global income
income = ic
def getIncome():
return income
def setWaterPrice(wp):
global waterPrice
waterPrice = wp
def getWaterPrice():
return waterPrice
def setElectricPrice(ep):
global electricPrice
electricPrice = ep
def getElectricPrice():
return electricPrice
def setGasPrice(gp):
global gasPrice
gasPrice = gp
def getGasPrice():
return gasPrice
def getUtilityBill():
result = waterPrice + electricPrice + gasPrice
return result
def getUtilityBillRate():
result = getUtilityBill() / getIncome() * 100
return result
import utilityBill as ub
inputIncome = int(input('수입 입력: '))
ub.setIncome(inputIncome)
inputWaterPrice = int(input('수도요금 입력: '))
ub.setWaterPrice(inputWaterPrice)
inputElectricPrice = int(input('전기요금 입력: '))
ub.setElectricPrice(inputElectricPrice)
inputGasPrice = int(input('가스요금 입력: '))
ub.setGasPrice(inputGasPrice)
print(f'공과금: {ub.getUtilityBill()}원')
print(f'수입 대비 공과금 비율: {ub.getUtilityBillRate()}%')
52. 모듈 (07) - 패키지 모듈 만들고 실행하기
from arithmetic import basic_operation as bo
from arithmetic import developer_operation as do
from shape import triangle_square_area as tsa
from shape import circle_area as ca
inputNumber1 = float(input('숫자1 입력: '))
inputNumber2 = float(input('숫자2 입력: '))
print(f'{inputNumber1} + {inputNumber2} = {bo.add(inputNumber1, inputNumber2)}')
print(f'{inputNumber1} - {inputNumber2} = {bo.sub(inputNumber1, inputNumber2)}')
print(f'{inputNumber1} * {inputNumber2} = {bo.mul(inputNumber1, inputNumber2)}')
print(f'{inputNumber1} / {inputNumber2} = {bo.div(inputNumber1, inputNumber2)}')
print(f'{inputNumber1} % {inputNumber2} = {do.mod(inputNumber1, inputNumber2)}')
print(f'{inputNumber1} // {inputNumber2} = {do.flo(inputNumber1, inputNumber2)}')
print(f'{inputNumber1} ** {inputNumber2} = {do.exp(inputNumber1, inputNumber2)}')
inputWidth = float(input('가로 길이 입력: '))
inputHeight = float(input('세로 길이 입력: '))
print(f'삼각형 넓이: {tsa.calTriangleArea(inputWidth, inputHeight)}')
print(f'사각형 넓이: {tsa.calSquareArea(inputWidth, inputHeight)}')
inputRadius = float(input('반지름 입력: '))
print(f'원의 넓이: {ca.calCircleArea(inputRadius)}')
53. 클래스 (01) - 회원가입 및 탈퇴
class Member:
def __init__(self, i, p):
self.id = i
self.pw = p
class MemberRepository:
def __init__(self):
self.members = {}
def addMember(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 success!!')
else:
print(f'{i}: log-in fail!!')
def removeMember(self, i, p):
if i in self.members:
if self.members[i] == p:
del self.members[i]
print('remove success!!')
else:
print('remove fail!!')
def printMembers(self):
for mk in self.members.keys():
print(f'ID: {mk}')
print(f'PW: {self.members[mk]}')
import member as mb
mems = mb.MemberRepository()
for i in range(3):
mID = input('아이디 입력: ')
mPw = input('비밀번호 입력: ')
mem = mb.Member(mID, mPw)
mems.addMember(mem)
mems.printMembers()
mems.loginMember('abc@gmail.com', '1234')
mems.loginMember('def@gmail.com', '5678')
mems.loginMember('ghi@gmail.com', 'c')
54. 클래스 (02) - 클래스 상속 및 객체 생성
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
import smartTV as st
my8kTv = st.Tv8k('75', 'black', '8k')
my8kTv.setSmartTv('on')
my8kTv.setAiTv('on')
my8kTv.turnOn()
my8kTv.printTvInfo()
my8kTv.turnOff()
friend8kTv = st.Tv8k('86', 'red', '8k')
friend8kTv.setSmartTv('on')
friend8kTv.setAiTv('off')
friend8kTv.turnOn()
friend8kTv.printTvInfo()
friend8kTv.turnOff()
55. 클래스 (03) - 도서 정보 및 저장소
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.bIsbn] = b
def removeBook(self, isbn):
del self.bDic[isbn]
def printBooksInfo(self):
for isbn in self.bDic.keys():
b = self.bDic[isbn]
print(f'{b.bName}, {b.bPrice}, {b.bIsbn}')
def printBookInfo(self, isbn):
if isbn in self.bDic:
b = self.bDic[isbn]
print(f'{b.bName}, {b.bPrice}, {b.bIsbn}')
else:
print('Lookup result does not exist.')
import book as bk
myBRepository = bk.BookRepository()
myBRepository.registbook(bk.Book('python', 20000, '12345678'))
myBRepository.registbook(bk.Book('java', 25000, '89833040'))
myBRepository.registbook(bk.Book('c/c++', 27000, '23456789'))
myBRepository.printBooksInfo()
print()
myBRepository.printBookInfo('23456789')
myBRepository.removeBook('23456789')
myBRepository.printBooksInfo()
56. 클래스 (04) - 추상 클래스를 이용하여 사전 만들기
from abc import ABCMeta
from abc import abstractmethod
class AbsDictionary(metaclass=ABCMeta):
def __init__(self):
self.wordDic = {}
@abstractmethod
def registWord(self, w1, w2):
pass
@abstractmethod
def removeWord(self, w1):
pass
@abstractmethod
def updateWord(self, w1, w2):
pass
@abstractmethod
def searchWord(self, w1):
pass
class KorToEng(AbsDictionary):
def __init__(self):
super().__init__()
def registWord(self, w1, w2):
print(f'[KorToEng] registWord() : {w1} to {w2}')
self.wordDic[w1] = w2
def removeWord(self, w1):
print(f'[KorToEng] removeWord() : {w1}')
del self.wordDic[w1]
def updateWord(self, w1, w2):
print(f'[KorToEng] updateWord() : {w1} to {w2}')
self.wordDic[w1] = w2
def searchWord(self, w1):
print(f'[KorToEng] searchWord() : {w1}')
return self.wordDic[w1]
def printWords(self):
for k in self.wordDic.keys():
print(f'{k}: {self.wordDic[k]}')
import ADictionary as dic
kTe = dic.KorToEng()
kTe.registWord('책', 'bok')
kTe.registWord('나비', 'butterfly')
kTe.registWord('연필', 'pencil')
kTe.registWord('학생', 'student')
kTe.registWord('선생님', 'teacher')
kTe.printWords()
kTe.updateWord('책', 'book')
kTe.printWords()
print(f'책 : {kTe.searchWord("책")}')
print(f'나비 : {kTe.searchWord("나비")}')
print(f'선생님 : {kTe.searchWord("선생님")}')
kTe.removeWord('책')
kTe.printWords()
57. 클래스 (05) - 주사위 게임 클래스
import random as rd
class Dice:
def __init__(self):
self.cNum = 0
self.uNum = 0
def setCnum(self):
print('[Dice] setGame()')
self.cNum = rd.randint(1, 6)
def setUnum(self):
print('[Dice] setGame()')
self.uNum = rd.randint(1, 6)
def startGame(self):
print('[Dice] startGame()')
self.setCnum()
self.setUnum()
def printResult(self):
print('[Dice] printResult()')
if self.cNum == 0 or self.uNum == 0:
print('주사위 숫자 선정 전 입니다.')
else:
if self.cNum > self.uNum:
print(f'컴퓨터 VS 유저 : {self.cNum} vs {self.uNum} >> 컴퓨터 승!!')
elif self.cNum < self.uNum:
print(f'컴퓨터 VS 유저 : {self.cNum} vs {self.uNum} >> 유저 승!!')
elif self.cNum == self.uNum:
print(f'컴퓨터 VS 유저 : {self.cNum} vs {self.uNum} >> 무승부!!')
import dice
dc = dice.Dice()
dc.startGame()
dc.printResult()
58. 클래스 (06) - 자동차 경주 게임(패키지 사용)
import random
class Car:
def __init__(self, n='fire car', c='red', s=200):
self.name = n
self.color = c
self.max_speed = s
self.distance = 0
def printCarInfo(self):
print(f'name: {self.name}, color: {self.color}, max_speed: {self.max_speed}')
def controlSpeed(self):
return random.randint(0, self.max_speed)
def getDistanceForHour(self):
return self.controlSpeed() * 1
from time import sleep
class CarRacing:
def __init__(self):
self.cars = []
self.rankings = []
def startRacing(self):
for i in range(10):
print(f'Racing: {i+1}바퀴')
for car in self.cars:
car.distance += car.getDistanceForHour()
sleep(1)
self.printCurrentCarDistance()
def printCurrentCarDistance(self):
for car in self.cars:
print(f'{car.name} : {car.distance} \t\t', end='')
print()
def addCar(self, c):
self.cars.append(c)
from car_game import racing as rc
from car_game import car
myCarGame = rc.CarRacing()
car01 = car.Car('Car01', 'White', 250)
car02 = car.Car('Car02', 'Black', 200)
car03 = car.Car('Car03', 'Yellow', 220)
car04 = car.Car('Car04', 'Red', 280)
car05 = car.Car('Car05', 'Blue', 150)
myCarGame.addCar(car01)
myCarGame.addCar(car02)
myCarGame.addCar(car03)
myCarGame.addCar(car04)
myCarGame.addCar(car05)
myCarGame.startRacing()
59. 클래스 (07) - mp3 플레이어 재생
import random
from time import sleep
class Song:
def __init__(self, t, s, pt):
self.title = t
self.singer = s
self.play_time = pt
def printSongInfo(self):
print(f'Title: {self.title}, Singer; {self.singer}, Play time: {self.play_time}')
class Player:
def __init__(self):
self.songList = []
self.isLoop = False
def addSong(self, s):
self.songList.append(s)
def play(self):
if self.isLoop:
while self.isLoop:
for s in self.songList:
print(f'Title: {s.title}, Singer: {s.singer}, Play time: {s.play_time}sec')
sleep(s.play_time)
else:
for s in self.songList:
print(f'Title: {s.title}, Singer: {s.singer}, Play time: {s.play_time}sec')
sleep(s.play_time)
def suffle(self):
random.shuffle(self.songList)
def setIsLoop(self, flag):
self.isLoop = flag
import mp3player as mp3
s1 = mp3.Song('신호등', '이무진', 3)
s2 = mp3.Song('Permission', '방탄소년단', 4)
s3 = mp3.Song('Butter', '방탄소년단', 2)
s4 = mp3.Song('Weekend', '태연', 5)
s5 = mp3.Song('좋아좋아', '조정석', 4)
player = mp3.Player()
player.addSong(s1)
player.addSong(s2)
player.addSong(s3)
player.addSong(s4)
player.addSong(s5)
player.setIsLoop(False)
player.suffle()
player.play()
60. 예외처리 (01)
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
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}')
import calculator as cc
num1 = input('첫 번째 피연산자 입력: ')
num2 = input('두 번째 피연산자 입력: ')
cc.exp(num1, num2)
61. 예외처리 (02)
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)
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}')
62. 예외처리 (03)
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)
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'총 구매 금액: {formatedNumber(totalPrice)}원')
print('------------------------미결제 항목------------------------')
for g in againCntInput.keys():
print(f'상품: {g}, \t 구매 개수: {againCntInput}')
print('------------------------------------------------')
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)
63. 예외처리 (04)
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}')
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)
64. 예외처리 (05) - 은행 계좌 개설 및 출금
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 deDeposit(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}')
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.deDeposit(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('잘못 입력했습니다. 다시 선택하세요.')
65. 텍스트 파일 (01) - readlines()
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, d):
filePath = u + f
datas = []
with open(filePath,'r') as f:
datas = f.readlines()
return datas
import diary
members = {}
uri = '/Users/user1/Downloads/pythonEx/'
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'
data = 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, data)
for d in datas:
print(d, end='')
else:
print('login fail!!')
printMembers()
elif selectNum == 4:
print('Bye~')
break
66. 텍스트 파일 (02) - 수입, 지출 기록 가계부(r, w, a)
import time
def getTime():
lt = time.localtime()
st = time.strftime('%Y-%m-%d %H:%M:%S')
return st
while True:
selectNumber = int(input('1.입금, \t 2.출금, \t 3.종료'))
if selectNumber == 1:
money = int(input('입금액 입력: '))
with open('/Users/user1/Downloads/pythonEx/pythonTxt/bank.txt', 'r') as f:
m = f.read()
with open('/Users/user1/Downloads/pythonEx/pythonTxt/bank.txt', 'w') as f:
f.write(str(int(m) + money))
memo = input('입금 내역 입력: ')
with open('/Users/user1/Downloads/pythonEx/pythonTxt/poketMoneyRegister.txt', 'a') as f:
f.write('-----------------------------------------------')
f.write(f'{getTime()} \n')
f.write(f'[입금] {memo} : {str(money)}원 \n')
f.write(f'[잔액] : {str(int(m) + money)}원 \n')
print('입금 완료!!')
print(f'입금 후 잔액: {int(m) + money}')
elif selectNumber == 2:
money = int(input('출금액 입력: '))
with open('/Users/user1/Downloads/pythonEx/pythonTxt/bank.txt', 'r') as f:
m = f.read()
with open('/Users/user1/Downloads/pythonEx/pythonTxt/money.txt', 'w') as f:
f.write(str(int(m) - money))
memo = input('출금 내역 입력: ')
with open('/Users/user1/Downloads/pythonEx/pythonTxt/poketMoneyRegister.txt', 'a') as f:
f.write('-----------------------------------------------')
f.write(f'{getTime()} \n')
f.write(f'[출금] {memo} : {str(money)}원 \n')
f.write(f'[잔액] : {str(int(m) - money)}원 \n')
print('출근 완료!!')
print(f'출금 후 잔액: {int(m) - money}')
67. 텍스트 파일 (03) - 소수 기록
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('/Users/user1/Downloads/pythonEx/pythonTxt/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!!')
68. 텍스트 파일 (04) - 공약수, 최대공약수 구하기
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('/Users/user1/Downloads/pythonEx/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('/Users/user1/Downloads/pythonEx/pythonTxt/maxComNum.txt', 'a') as f:
f.write(f'{num1}과 {num2}의 최대공약수: {maxComNum} \n')
except Exception as e:
print(e)
else:
print('max common factor write complete!!')
69. 텍스트 파일 (05) - 최대공약수(선박 입항 주기)
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('/Users/user1/Downloads/pythonEx/pythonTxt/arrive.txt', 'a') as f:
f.write(f'2021년 모든 선박 입항일\n')
f.write(f'{baseTime}\n')
nextTime = baseTime + timedelta(days=minDay)
while True:
with open('/Users/user1/Downloads/pythonEx/pythonTxt/arrive.txt', 'a') as f:
f.write(f'{nextTime}\n')
nextTime = nextTime + timedelta(days=minDay)
if nextTime.year > 2021:
break