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 flo(n1, n2):
return n1 // n2
def mod(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. 종료\t'))
if selectNum == 8:
print('Bye~')
break
elif selectNum == 1:
num1 = float(input('첫 번째 숫자 입력: '))
num2 = float(input('두 번째 숫자 입력: '))
print(f'{num1} + {num2} = {add(num1, num2)}')
elif selectNum == 2:
num1 = float(input('첫 번째 숫자 입력: '))
num2 = float(input('두 번째 숫자 입력: '))
print(f'{num1} - {num2} = {sub(num1, num2)}')
elif selectNum == 3:
num1 = float(input('첫 번째 숫자 입력: '))
num2 = float(input('두 번째 숫자 입력: '))
print(f'{num1} * {num2} = {mul(num1, num2)}')
elif selectNum == 4:
num1 = float(input('첫 번째 숫자 입력: '))
num2 = float(input('두 번째 숫자 입력: '))
print(f'{num1} / {num2} = {div(num1, num2)}')
elif selectNum == 5:
num1 = float(input('첫 번째 숫자 입력: '))
num2 = float(input('두 번째 숫자 입력: '))
print(f'{num1} // {num2} = {flo(num1, num2)}')
elif selectNum == 6:
num1 = float(input('첫 번째 숫자 입력: '))
num2 = float(input('두 번째 숫자 입력: '))
print(f'{num1} % {num2} = {mod(num1, num2)}')
elif selectNum == 7:
num1 = float(input('첫 번째 숫자 입력: '))
num2 = float(input('두 번째 숫자 입력: '))
print(f'{num1} ** {num2} = {exp(num1, num2)}')
else:
print('잘 못 입력하셨습니다. 다시 입력해주세요.')
print('-' * 60)
def getDistance(speed, hour, minute):
distance = speed * (hour + minute / 60)
return distance
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}(m)분 동안 이동한 거리: {d}(km)')
print('-' * 60)
def getTime(speed, distance):
time = distance / speed * 60
hr = int(time // 60)
min = int(time - hr * 60)
return [hr, min]
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)
def getTime(speed, distance):
time = distance / speed
h = int(time)
m = int((time - h) * 100 * 60 / 100)
return [h, m]
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)
childPrice = 18000
infantPrice = 25000
adultPrice = 50000
specialDC = 50
def formattedNum(n):
return format(n, ',')
def printAirplaneReceipt(c1, c2, i1, i2, a1, a2):
print('=' * 60)
cp = c1 * childPrice
cp_dc = int(c2 * childPrice * 0.5)
print(f'유아 {c1}명 요금: {formattedNum(cp)}원')
print(f'유아 할인 대상 {c2}명 요금: {formattedNum(cp_dc)}원')
ip = i1 * infantPrice
ip_dc = int(i2 * infantPrice * 0.5)
print(f'소아 {i1}명 요금: {formattedNum(ip)}원')
print(f'소아 할인 대상 {i2}명 요금: {formattedNum(ip_dc)}원')
ap = a1 * adultPrice
ap_dc = int(a2 * adultPrice * 0.5)
print(f'성인 {a1}명 요금: {formattedNum(ap)}원')
print(f'성인 할인 대상 {a2}명 요금: {formattedNum(ap_dc)}원')
print('=' * 60)
print(f'Total: {c1 + c2 + i1 + i2 + a1 + a2}명')
print(f'TotalPrice: {formattedNum(cp + cp_dc + ip + ip_dc + ap + ap_dc)}원')
print('=' * 60)
childCnt = int(input('유아 입력: '))
specialDCChildCtn = int(input('할인 대상 유아 입력: '))
infantCnt = int(input('소아 입력: '))
specialDCInfantCnt = int(input('할인 대상 소아 입력: '))
adultCnt = int(input('성인 입력: '))
specialDCAdultCnt = int(input('할인 대상 성인 입력: '))
printAirplaneReceipt(childCnt, specialDCChildCtn,
infantCnt, specialDCInfantCnt,
adultCnt, specialDCAdultCnt)
def formattedNum(n):
return format(n, ',')
# 단리
def singleRateCal(m, t, r):
totalMoney = 0
totalRateMoney = 0
for i in range(t):
totalRateMoney += m * (r * 0.01)
totalMoney = m + totalRateMoney
return int(totalMoney)
# 복리
def mulRateCal(m, t, r):
t = t * 12
rpm = (r / 12) * 0.01
totalMoney = m
for i in range(t):
totalMoney += totalMoney * rpm
return int(totalMoney)
money = int(input('예치금: '))
term = int(input('기간(년): '))
rate = int(input('연 이율(%): '))
print('\n')
print('[단리 계산기]')
print('=' * 60)
print(f'예치금\t: {formattedNum(money)}원')
print(f'예치기간\t: {term}년')
print(f'예치금\t: {rate}%')
print('-' * 60)
print(f'{term}년 후 총 수령액: {formattedNum(singleRateCal(money, term, rate))}원')
print('=' * 60)
print('\n')
print('[복리 계산기]')
print('=' * 60)
print(f'예치금\t: {formattedNum(money)}원')
print(f'예치기간\t: {term}년')
print(f'예치금\t: {rate}%')
print('-' * 60)
print(f'{term}년 후 총 수령액: {formattedNum(mulRateCal(money, term, rate))}원')
print('=' * 60)
# 등차 수열 공식 : an = a1 + (n-1) * d
# 등차 수열 합 공식 : sn = n * (a1 + an) / 2
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)
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)
# passOrFail 모듈
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 s2 >= limitScore else print(f'{s2}: Fail')
print(f'{s3}: Pass') if s3 >= limitScore else print(f'{s3}: Fail')
print(f'{s4}: Pass') if s4 >= limitScore else print(f'{s4}: Fail')
print(f'{s5}: Pass') if s5 >= 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()
# main 파일
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)
# 할인 모듈
def calTotalPrice(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)]
# main 모듈
import discount as dc
if __name__ == '__main__':
flag = True
gs = []
while flag:
selectNum = int(input('1.구매, 2.종료: '))
if selectNum == 1:
goods_price = int(input('상품 가격 입력: '))
gs.append(goods_price)
elif selectNum == 2:
result = dc.calTotalPrice(gs)
flag = False
print(f'할인율: {result[0]}%')
print(f'합계: {result[1]}원')
# 로또 모듈
import random
userNums = []; randNums = []; collNums = []
randBonusNum = 0
def setUserNum(ns):
global userNums
userNums = ns
def getUserNums():
return userNums
def setRandNums():
global randNums
randNums = random.sample(range(1, 46), 6)
def getRandNums():
return randNums
def setBonusNum():
global randBonusNum
while True:
randBonusNum = random.randint(1, 45)
if randBonusNum not in randNums:
break
def getBonusNum():
return randBonusNum
def lotteryResult():
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 (randBonusNum in userNums):
print('2등 당첨!!')
print(f'번호: {collNums}, 보너스 번호: {randBonusNum}')
elif len(collNums) == 5:
print('3등 당첨!!')
print(f'번호: {collNums}')
elif len(collNums) == 4:
print('4등 당첨!!')
print(f'번호: {collNums}')
else:
print('아쉽습니다. 다음 기회에!')
print(f'기계 번호: {randNums}')
print(f'보너스 번호: {randBonusNum}')
print(f'선택 번호: {userNums}')
print(f'일치 번호: {collNums}')
def startLottery():
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()
setBonusNum()
lotteryResult()
# main 모듈
import lottery as lt
lt.startLottery()
# permutation 모듈
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
# main 모듈
import permutation as pt
numN = int(input('numN 입력: '))
numR = int(input('numR 입력: '))
# print(f'{numN}P{numR}: {pt.getPermutationCnt(numN, numR, logPrint=True)}')
# permutation 모듈
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='')
# main 모듈
listVar = [1, 2, 3, 4, 5, 6, 7, 8]
rVar = 3
pt.getPermutations(listVar, rVar)
# combination 모듈
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'result: {resultC}')
return resultC
# main 모듈
import combinations as cb
numN = int(input('numN 입력: '))
numR = int(input('numR 입력: '))
print(f'{numN}C{numR}: {cb.getCombinationCnt(numN, numR, logPrint=True)}')
# combination 모듈
from itertools import combinations
def getCombination(ns, r):
cList = list(combinations(ns, r))
print(f'{len(ns)}C{r}: {len(cList)}')
# main 모듈
listVar = [1, 2, 3, 4, 5, 6, 7, 8]
rVar = 3
cb.getCombination(listVar, rVar)
# 공과금 모듈
income = 0
waterPrice = 0; elecPrice = 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 setElecPrice(ep):
global elecPrice
elecPrice = ep
def getElecPrice():
return elecPrice
def setGasPrice(gp):
global gasPrice
gasPrice = gp
def getGasPrice():
return gasPrice
def getUtilityBill():
result = waterPrice + elecPrice + gasPrice
return result
def getUtilityBillRate():
result = getUtilityBill() / getIncome() * 100
return result
def formattedNum(n):
return format(n, ',')
# main 모듈
import utilityBill as ub
inputIncome = int(input('수입 입력: '))
ub.setIncome(inputIncome)
inputWaterPrice = int(input('수도요금 입력: '))
ub.setWaterPrice(inputWaterPrice)
inputElecPrice = int(input('전기요금 입력: '))
ub.setElecPrice(inputElecPrice)
inputGasPrice = int(input('갸스요금 입력: '))
ub.setGasPrice(inputGasPrice)
print(f'공과금: {ub.formattedNum(ub.getUtilityBill())}원')
print(f'수입 대비 공과금 비율: {ub.getUtilityBillRate()}%')
# basic_operator 모듈
def add(n1, n2):
return round(n1 + n2, 2)
def sub(n1, n2):
return round(n1 - n2, 2)
def mul(n1, n2):
return round(n1 * n2, 2)
def div(n1, n2):
return round(n1 / n2, 2)
# developer_operator 모듈
def mod(n1, n2):
return round(n1 % n2, 2)
def flo(n1, n2):
return round(n1 // n2, 2)
def exp(n1, n2):
return round(n1 ** n2, 2)
# circle_area 모듈
def calCircleArea(r):
return round(r ** 2 * 3.14, 2)
# triangle_square_area 모듈
def calTriArea(w, h):
return round(w * h / 2, 2)
def calSquareArea(w, h):
return round(w * h, 2)
# main 모듈
from arithmetic import basic_operator as bo
from arithmetic import developer_operator as do
from shape import circle_area as ca
from shape import triangle_square_area as tsa
inputNum1 = float(input('숫자1 입력: '))
inputNum2 = float(input('숫자2 입력: '))
print(f'{inputNum1} + {inputNum2} = {bo.add(inputNum1, inputNum2)}')
print(f'{inputNum1} - {inputNum2} = {bo.sub(inputNum1, inputNum2)}')
print(f'{inputNum1} * {inputNum2} = {bo.mul(inputNum1, inputNum2)}')
print(f'{inputNum1} / {inputNum2} = {bo.div(inputNum1, inputNum2)}')
print(f'{inputNum1} % {inputNum2} = {do.mod(inputNum1, inputNum2)}')
print(f'{inputNum1} // {inputNum2} = {do.flo(inputNum1, inputNum2)}')
print(f'{inputNum1} ** {inputNum2} = {do.exp(inputNum1, inputNum2)}')
inputWidth = float(input('가로 길이 입력: '))
inputHeight = float(input('세로 길이 입력: '))
print(f'삼각형 넓이: {tsa.calTriArea(inputWidth, inputHeight)}')
print(f'사각형 넓이: {tsa.calSquareArea(inputWidth, inputHeight)}')
inputRadius = float(input('반지름 길이 입력: '))
print(f'원 넓이: {ca.calCircleArea(inputRadius)}')
# 회원가입 클래스
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):
del self.members[i]
def printMembers(self):
for mk in self.members.keys():
print(f'ID: {mk}')
print(f'PW: {self.members[mk]}')
# main 모듈
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', '9012')
mems.removeMember('abc@gmail.com', '1234')
mems.printMembers()
# 스마트 티비 클래스
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
# main 모듈
import smartTV as st
my4kTv = st.Tv4k('65', 'silver', '4k')
my4kTv.setSmartTv('on')
my4kTv.turnOn()
my4kTv.printTvInfo()
my4kTv.turnOff()
print('=' * 60)
friend4kTv = st.Tv4k('55', 'white', '4k')
friend4kTv.setSmartTv('off')
friend4kTv.turnOn()
friend4kTv.printTvInfo()
friend4kTv.turnOff()
print('=' * 60)
my8kTV = st.Tv8k('75', 'black', '8k')
my8kTV.setSmartTv('on')
my8kTV.setAiTv('on')
my8kTV.turnOn()
my8kTV.printTvInfo()
my8kTV.turnOff()
print('=' * 60)
friend8kTV = st.Tv8k('86', 'red', '8k')
friend8kTV.setSmartTv('on')
friend8kTV.setAiTv('off')
friend8kTV.turnOn()
friend8kTV.printTvInfo()
friend8kTV.turnOff()
# 도서 관리 클래스
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.')
# main 모듈
import book as bk
myBRepository = bk.BookRepository()
myBRepository.registBook(bk.Book('python', 20000, '1234567890'))
myBRepository.registBook(bk.Book('java', 25000, '3434232588'))
myBRepository.registBook(bk.Book('c/c++', 27000, '8658735421'))
myBRepository.printBooksInfo()
print()
myBRepository.printBookInfo('1234567890')
myBRepository.printBookInfo('3434232588')
myBRepository.printBookInfo('8658735421')
myBRepository.removeBook('1234567890')
print()
myBRepository.printBooksInfo()
print()
friendBRepository = bk.BookRepository()
friendBRepository.registBook(bk.Book('ruby', 20000, '1234567890'))
friendBRepository.registBook(bk.Book('c#', 25000, '3434232588'))
friendBRepository.registBook(bk.Book('linux', 27000, '8658735421'))
friendBRepository.printBooksInfo()
print()
friendBRepository.printBookInfo('1234567890')
friendBRepository.printBookInfo('3434232588')
friendBRepository.printBookInfo('8658735421')
friendBRepository.removeBook('1234567890')
friendBRepository.printBooksInfo()
# 한영 & 한일 사전 클래스
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]}')
class KorToJpn(AbsDictionary):
def __init__(self):
super().__init__()
def registWord(self, w1, w2):
print(f'[KorToJpn] registWord() : {w1} to {w2}')
self.wordDic[w1] = w2
def removeWord(self, w1):
print(f'[KorToJpn] removeWord() : {w1}')
del self.wordDic[w1]
def updateWord(self, w1, w2):
print(f'[KorToJpn] updateWord() : {w1} to {w2}')
self.wordDic[w1] = w2
def searchWord(self, w1):
print(f'[KorToJpn] searchWord() : {w1}')
return self.wordDic[w1]
def printWords(self):
for k in self.wordDic.keys():
print(f'{k} = {self.wordDic[k]}')
# main 모듈
import ADictionary as dic
k2e = dic.KorToEng()
k2e.registWord('책', 'bok')
k2e.registWord('나비', 'butterfly')
k2e.registWord('연필', 'pencil')
k2e.registWord('학생', 'student')
k2e.registWord('선생님', 'teacher')
k2e.printWords()
k2e.updateWord('책', 'book')
k2e.printWords()
print(f'{k2e.searchWord("책")}')
print(f'{k2e.searchWord("나비")}')
print(f'{k2e.searchWord("연필")}')
k2e.removeWord('책')
k2e.printWords()
# 주사위 게임 클래스
import random as rd
class Dice:
def __init__(self):
self.cNum = 0
self.uNum = 0
def setCNum(self):
print('[Dice] setCNum()')
self.cNum = rd.randint(1, 6)
def setUNum(self):
print('[Dice] setUNum()')
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} --> 무승부!!')
# main 모듈
import dice as d
dc = d.Dice()
dc.startGame()
dc.printResult()
# car 클래스
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
# racing 클래스
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)
# main 모듈
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', 220)
car03 = car.Car('Car03', 'Yellow', 180)
car04 = car.Car('Car04', 'Red', 200)
car05 = car.Car('Car05', 'Blue', 230)
myCarGame.addCar(car01)
myCarGame.addCar(car02)
myCarGame.addCar(car03)
myCarGame.addCar(car04)
myCarGame.addCar(car05)
myCarGame.startRacing()
# mp3 플레이어 클래스
from time import sleep
import random
class Song:
def __init__(self, t, s, pt):
self.title = t
self.singer = s
self.play_time = pt
def printSongInfo(self):
print(f'Tile: {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'Tile: {s.title}, Singer: {s.singer}, Play Time: {s.play_time}sec')
sleep(s.play_time)
else:
for s in self.songList:
print(f'Tile: {s.title}, Singer: {s.singer}, Play Time: {s.play_time}sec')
sleep(s.play_time)
def shuffle(self):
random.shuffle(self.songList)
def setIsLoop(self, flag):
self.isLoop = flag
# main 모듈
import mp3Player as mp3
s1 = mp3.Song('That\'s Love', 'Marc E. Bassy', 3.30)
s2 = mp3.Song('Paranoid', 'Ty Dolla $ign', 3.25)
s3 = mp3.Song('Take it there', 'Tone Stith (feat.Ty Dolla $ign', 3.48)
s4 = mp3.Song('Beep', 'Ant Clemons', 3.18)
s5 = mp3.Song('Demons', 'Imagine Dragons', 3.20)
player = mp3.Player()
player.addSong(s1)
player.addSong(s2)
player.addSong(s3)
player.addSong(s4)
player.addSong(s5)
player.setIsLoop(False)
player.shuffle()
player.play()
# 계산기 모듈
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
# if n2 == 0:
# print('0으로 나눌 수 없습니다.')
# 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
try:
print(f'{n1} % {n2} = {n1 % n2}')
except ZeroDivisionError as e:
print(e)
print('0으로 나눌 수 없습니다.')
def flo(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 exp(n1, n2):
print('거듭제곱 연산')
try:
n1 = float(n1)
except:
print('첫 번째 피연산자는 숫자가 아닙니다.')
return
try:
n2 = float(n2)
except:
print('두 번째 피연산자는 숫자가 아닙니다.')
return
print(f'{n1} ** {n2} = {n1 ** n2}')
# main 모듈
import calculator as cc
num1 = input('첫 번째 피연산자: ')
num2 = input('두 번째 피연산자: ')
cc.add(num1, num2)
cc.sub(num1, num2)
cc.mul(num1, num2)
cc.div(num1, num2)
cc.mod(num1, num2)
cc.flo(num1, num2)
cc.exp(num1, num2)
# 소수 프로그램
class NotPrimeException(Exception):
def __init__(self, n):
super().__init__(f'{n} is not a prime number.')
class IsPrimeException(Exception):
def __init__(self, n):
super().__init__(f'{n} is a 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 IsPrimeException(number)
# main 모듈
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.IsPrimeException as e:
print(e)
primeNumbers.append(rn)
else:
print(f'{rn} is an overlapped number.')
continue
n += 1
print(f'prime numbers: {primeNumbers}')
# 구매 프로그램
g1Price = 1200;
g2Price = 1000;
g3Price = 800
g4Price = 2000;
g5Price = 900
def formattedNumber(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('-' * 70)
print(f'총 구매 금액: {formattedNumber(totalPrice)}원')
print('-' * 30, '미결제 항목', '-' * 30)
for g in againCntInput.keys():
print(f'상품: {g}, \t 구매 개수: {againCntInput[g]}')
print('-' * 70)
# main 모듈
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)
# 회원가입 프로그램
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 Register 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}')
# main 모듈
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)
# 은행 입/출금 프로그램
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('-' * 60)
print(f'account_name" {self.account_name}')
print(f'account_no" {self.account_no}')
print(f'totalMoney" {self.totalMoney}')
print('-' * 60)
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 = pb.totalMoney + m
def dopWithdraw(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}')
# main 모듈
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.dopWithdraw(myAccount.account_no, m)
except bank.LackException as e:
print(e)
finally:
myAccount.printBankInfo()
elif selectNumber == 3:
print('Bye')
break
else:
print('잘 못 입력하셨습니다. 다시 선택해주세요.')
# 일기 프로그램
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
# main 모듈
import diary
members = {}
uri = '/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/'
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
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)
for d in datas:
print(d, end='')
else:
print('Login Fail!')
elif selectNum == 4:
print('Bye!')
break
import time
def getTime():
lt = time.localtime()
st = time.strftime('%Y-%m-%d %H:%M:%S')
return st
while True:
selectNum = int(input('1.입금, \t2.출금, \t3.종료\t'))
if selectNum == 1:
money = int(input('입금액 입력: '))
with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/money.txt', 'r') as f:
m = f.read()
with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/money.txt', 'w') as f:
f.write(str(int(m) + money))
memo = input('입금 내역 입력: ')
with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/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 selectNum == 2:
money = int(input('출금액 입력: '))
with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/money.txt', 'r') as f:
m = f.read()
with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/money.txt', 'w') as f:
f.write(str(int(m) - money))
memo = input('출금 내역 입력: ')
with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/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 selectNum == 3:
print('Bye~')
break
else:
print('잘 못 입력하셨습니다. 다시 입력해주세요.')
inputNum = int(input('0보다 큰 정수 입력: '))
divisor = []
for number in range(1, (inputNum +1)):
if inputNum % number == 0:
divisor.append(number)
if len(divisor) > 0:
try:
with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/divisor.txt', 'a') as f:
f.write(f'{inputNum}의 약수: ')
f.write(f'{divisor}\n')
except Exception as e:
print(e)
else:
print('divisor write complete!')
inputNum = int(input('0보다 큰 정수 입력: '))
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('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/prime.txt', 'a') as f:
f.write(f'{inputNum}까지의 소수: ')
f.write(f'{prime}\n')
except Exception as e:
print(e)
else:
print('prime number write complete!')
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/juneleekorea/Desktop/Life/zerobase/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보다 큰 정수 입력: '))
maxCoNum = []
for i in range(1, (num1 +1)):
if num1 % i == 0 and num2 % i == 0:
maxCoNum = i
try:
with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/maxCoNum.txt', 'a') as f:
f.write(f'{num1}과 {num2}의 공약수 : {maxCoNum}\n')
except Exception as e:
print(e)
else:
print('max common factor write complete!!')
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/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/arrival.txt', 'a') as f:
f.write(f'2023년 모든 선박 입항일\n')
f.write(f'{baseTime}\n')
nextTime = baseTime + timedelta(days=minDay)
while True:
with open('/Users/juneleekorea/Desktop/Life/zerobase/pythonEx/pythonTxt/arrival.txt', 'a') as f:
f.write(f'{nextTime}\n')
nextTime = nextTime + timedelta(days=minDay)
if nextTime.year > 2021:
break
이상 데이터 취업 스쿨 Day 7의 스터디노트이다.
이미지 출처: @waterglasstoon, 제로베이스 강의 일부