calculator 모듈
def add(n1, n2): print('덧셈 연산') try: n1 = float(n1) except: print('첫 번째 피연산자는 숫자가 아닙니다') return try: n2 = float(n2) except: print('두 번째 피연산자는 숫자가 아닙니다') return print('{} + {} = {}'.format(n1, n2, n1 + n2))
def sub(n1, n2): print('뺄셈 연산') try: n1 = float(n1) except: print('첫 번째 피연산자는 숫자가 아닙니다') return try: n2 = float(n2) except: print('두 번째 피연산자는 숫자가 아닙니다') return print('{} - {} = {}'.format(n1, n2, n1 - n2))
def mul(n1, n2): print('곱셈 연산') try: n1 = float(n1) except: print('첫 번째 피연산자는 숫자가 아닙니다') return try: n2 = float(n2) except: print('두 번째 피연산자는 숫자가 아닙니다') return print('{} * {} = {}'.format(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('{} / {} = {}'.format(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} = {int(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}')
ex.py
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)
prime_module
class NotPrimeException(Exception): def __init__(self, n): super().__init__('{} is not prime number'.format(n))
class PrimeException(Exception): def __init__(self, n): super().__init__('{} is prime number'.format(n))
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.py
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('{} is overlap number'.format(rn)) continue n += 1
print('PrimeNumbers: {}'.format(primeNumbers))
calculatePurchase모듈
g1price = 1200; g2price = 1000; g3price = 800 g4price = 2000; g5price = 900
def formatedNumber(n): return format(n, ',')
def calculate(*gcs): gcsDic = {} againCntInput = {} for idx, gc in enumerate(gcs): try: gcsDic['g{}'.format(idx+1)] = int(gc) except Exception as e: againCntInput['g{}'.format(idx+1)] = gc print(e) totalPrice = 0
for g in gcsDic.keys(): totalPrice += globals()['{}price'.format(g)] * gcsDic[g] print('---------------------------') print('총 구매 금액: {}원'.format(formatedNumber(totalPrice))) print('-------- 미결제 항목 --------') for g in againCntInput.keys(): print('상품: {},\t 구매 개수: {}'.format(g, againCntInput[g])) print('---------------------------')
ex.py
import calculatePurchase as cp
g1Cnt = input('goods1 구매 개수: ') g2Cnt = input('goods2 구매 개수: ') g3Cnt = input('goods3 구매 개수: ') g4Cnt = input('goods4 구매 개수: ') g5Cnt = input('goods5 구매 개수: ')
cp.calculate(g1Cnt, g2Cnt, g3Cnt, g4Cnt, g5Cnt)
mem 모듈
class EmptyDataException(Exception): def __init__(self, i): super().__init__('{} is empty'.format(i)) 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 RegisteMember(): 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('m_name: {}'.format(self.m_name)) print('m_mail: {}'.format(self.m_mail)) print('m_password: {}'.format(self.m_password)) print('m_address: {}'.format(self.m_address)) print('m_phone: {}'.format(self.m_phone))
ex.py
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.RegisteMember(m_name, m_mail, m_pw, m_addr, m_phone) newMember.printMemberInfo() except mem.EmptyDataException as e: print(e)
bank 모듈
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.addAcount(self) def printBankInfo(self): print('-' * 40) print('account_name: {}'.format(self.account_name)) print('account_no: {}'.format(self.account_no)) print('totalMoney: {}원'.format(self.totalMoney)) print('-' * 40)
class Bank: def __init__(self): self.accounts = {} def addAccount(self, privateBank): self.accounts[privateBank.account_no] = privateBank def isAcount(self, ano): return ano in self.accounts def doDeposit(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__('잔고부족!!, 잔액: {}, 출금액: {}'.format(m1, m2))
ex.py
import bank
koreaBank = bank.Bank() new_account_name = input('통장 계설을 위한 예금주 입력: ') myAccount = bank.PrivateBank(koreaBank, new_account_name) myAccount.printBankInfo()
while True: selectNumber = int(input('1.입금, \t2.출금, \t3.종료 '))
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('잘못 입력했습니다. 다시 선택하세요. ')
diary 모듈
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('[{}] {}\n'.format(timeStr, d))
def readDiary(u, f): lt = time.localtime() timeStr = time.strftime('%Y-%m-%d %I:%M:%S %p', lt) filePath = u + f datas = [] with open(filePath, 'r') as f: datas = f.readlines() return datas
ex.py
import diary members = {} uri = 'C:/pythonTxt/'
def printMembers(): for m in members.keys(): print('ID: {} \t PW: {}'.format(m, members[m]))
while True: selectNum = int(input('1.회원가입,\t 2.한줄일기쓰기,\t 3.한줄일기보기,\t 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 = 'myDaiary_' + 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 = 'myDaiary_' + 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
ex.py
import time limitSpendMoney = 2000
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('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/pocketMoneyRegister.txt', 'a') as f: f.write('-------------------------------------------\n') f.write('{} \n'.format(getTime())) f.write('[입금] {} : {}원 \n'.format(memo, str(money))) f.write('[잔액] {}원 \n'.format(str(int(m) + money))) print('입금 완료!!') print('기존 잔액 : {}'.format(m)) print('입금 후 잔액 : {}'.format(int(m) + money))
elif selectNumber == 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/pocketMoneyRegister.txt', 'a') as f: f.write('-------------------------------------------\n') f.write('{} \n'.format(getTime())) f.write('[출금] memo : {}원 \n'.format(str(money))) f.write('[잔액] {}원 \n'.format(str(int(m) - money))) print('출금 완료!!') print('기존 잔액 : {}'.format(m)) print('출금 후 잔액 : {}'.format(int(m) - money))
elif selectNumber == 3: print('Bye~') break
else: print('잘못 입력하셨습니다.')
약수
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:/pythonTxt/divisor.txt', 'a') as f: f.write('{}의 약수: '.format(inputNumber)) f.write('{}\n'.format(divisor)) 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:/pythonTxt/prime.txt', 'a') as f: f.write('{}까지의 소수: '.format(inputNumber)) f.write('{}\n'.format(prime)) except Exception as e: print(e) else: print('prime write complete!')
ex.py
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('{}와 {}의 공약수: '.format(num1, num2)) f.write('{}\n'.format(common)) except Exception as e: print(e) else: print('common factor write complete!')
ex.py
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: maxNum = i try: with open('C:/pythonTxt/maxComNum.txt', 'a') as f: f.write('{}와 {}의 최대공약수: {}\n'.format(num1, num2, maxNum)) 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
from datetime import datetime from datetime import timedelta
n = 1 baseTime = datetime(2023, 1, 1, 10, 0, 0)
with open('C:/pythonTxt/arrive.txt', 'a') as f: f.write('2023년 모든 선박 입항일\n') f.write('{}\n'.format(baseTime))
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