[python] 문제풀이

svenskpotatis·2023년 8월 6일
0

데이터와 변수

사용자가 입력한 데이터의 길이를 출력하는 프로그램

userMsg = input('메시지 입력: ')
print('메시지 문자열 길이 : {}'.format(len(userMsg)))
  • len(): 문자 길이를 반환함
  • find(): 특정 문자열의 위치를 찾아 반환함. //string1.find('특정문자열')

체중(g)과 신장(cm)을 입력하면 BMI지수가 출력되는 프로그램

  • isdigit(): 숫자인지 확인(숫자이면 True, 아니면 False)
# BMI = 몸무게(kg) / (신장(m) * 신장(m))

weight = input('체중 입력(g): ')
height = input('신장 입력(cm): ')

if weight.isdigit():
    weight = int(weight) / 10

if height.isdigit():
    height = int(height) / 100

print('체중 : {}kg'.format(weight))
print('신장 : {}kg'.format(height))

bmi = weight/(height*height)
print('BMI : %f' % bmi)

키오스크에서 사용하는 언어 선택 프로그램

selectNumber = input('언어 선택(Choose your language): 1.한국어 \t 2.English')

if selectNumber == '1':
    menu = '1.샌드위치 \t 2.햄버거 \t 3.쥬스 \t 4.커피 \t 5.아이스크림'
elif selectNumber == '2':
    menu = '1.Sandwich \t 2.Hamburger \t 3.Juice \t 4.Coffee \t 5.Ice cream'

print(menu)
  • import datetime : 날짜, 시간 정보 알려주는 모듈
    //datetime.datetime.today()
    //datetime.datetime.today().year
    //datetime.datetime.today().day

연산자

상품 가격과 지불 금액을 입력하면 거스름돈을 계산하는 프로그램

money50000 = 50000; money10000 = 10000; money5000 = 5000; money1000 = 1000
money500 = 500; money100 = 100; money10 = 10

money50000Cnt = 0; money10000Cnt = 0; money5000Cnt = 0; money1000Cnt = 0
money500Cnt = 0; money100Cnt = 0; money10Cnt = 0

productPrice = int(input('상품 가격 입력: '))
payPrice = int(input('지불 금액: '))

if payPrice > productPrice:
    changeMoney = payPrice - productPrice
    changeMoney = (changeMoney//10)*10
    print('거스름돈: {}(원단위 절사)'.format(changeMoney))

if changeMoney > money50000:
    money50000Cnt = changeMoney//money50000
    changeMoney %= money50000

if changeMoney > money10000:
    money10000Cnt = changeMoney//money10000
    changeMoney %= money10000

if changeMoney > money5000:
    money5000Cnt = changeMoney//money5000
    changeMoney %= money5000

if changeMoney > money1000:
    money1000Cnt = changeMoney//money1000
    changeMoney %= money1000

if changeMoney > money500:
    money500Cnt = changeMoney//money500
    changeMoney %= money500

if changeMoney > money100:
    money100Cnt = changeMoney//money100
    changeMoney %= money100

if changeMoney > money10:
    money10Cnt = changeMoney//money10
    changeMoney %= money50000

print('-'*30)
print('50,000 {}장'.format(money50000Cnt))
print('10,000 {}장'.format(money10000Cnt))
print('5,000 {}장'.format(money5000Cnt))
print('1,000 {}장'.format(money1000Cnt))
print('500 {}장'.format(money500Cnt))
print('100 {}장'.format(money100Cnt))
print('10 {}장'.format(money10Cnt))
print('-'*30)

금액, 이율, 거치기간을 입력하면 복리계산하는 복리계산기 프로그램

money = int(input('금액 입력: '))
rate = float(input('이율 입력: '))
term = int(input('기간 입력: '))

targetMoney = money

for i in range(term):
    targetMoney += targetMoney * rate * 0.01

targetMoneyFormated = format(int(targetMoney), ',')

print('-'*30)
print('이율: {}'.format(rate))
print('원금: {}'.format(format(money, ',')))
print('{}년 후 금액: {}원'.format(term, targetMoneyFormated))
print('-'*30)

조건문

  • abs(숫자) => 절댓값
  • random.randint(a, b) //a와 b 사이 난수 생성

반복문

1부터 사용자가 입력한 정수까지의 합, 홀수의 합, 짝수의 합 그리고 팩토리얼을 출력하는 프로그램

fNum = int(input('정수 입력: '))

addSum = 0
for i in range(1, (fNum+1)):
    addSum += i

addSumFormated = format(addSum, ',')
print('합 결과: {}'.format(addSumFormated))

oddSum = 0
for i in range(1, (fNum + 1)):
    if i%2 != 0:
        oddSum += i

oddSumFormated = format(oddSum, ',')
print('홀수 합 결과: {}'.format(oddSumFormated))

evenSum = 0
for i in range(1, (fNum + 1)):
    if i%2 == 0:
        evenSum += i

evenSumFormated = format(evenSum, ',')
print('짝수 합 결과: {}'.format(evenSumFormated))

factorialResult = 1
for i in range(1, (fNum + 1)):
    factorialResult *= i

factorialResultFormated = format(factorialResult, ',')
print('팩토리얼 결과: {}'.format(factorialResultFormated))

함수

계산기

def calculator(num):
    n1 = float(input("첫 번째 숫자 입력: "))
    n2 = float(input('두 번째 숫자 입력: '))
    if num==1:
        print(f'{n1} + {n2} = {n1+n2}')
    elif num==2:
        print(f'{n1} - {n2} = {n1 - n2}')
    elif num==3:
        print(f'{n1} * {n2} = {n1*n2}')
    elif num==4:
        print(f'{n1} / {n2} = {n1/n2}')
    elif num==5:
        print(f'{n1} % {n2} = {n1%n2}')
    elif num==6:
        print(f'{n1} // {n2} = {n1//n2}')
    elif num == 7:
        print(f'{n1} ** {n2} = {n1 ** n2}')

while True:
    print("-"*70)
    num = int(input('1. 덧셈, 2. 뺄셈, 3. 곱셈, 4. 나눗셈, 5. 나머지, 6. 몫, 7. 제곱승, 8. 종료'))
    if num==8:
        print('Bye~')
        break
    calculator(num)
    print("-" * 70)

//강의 해설: return, math 활용하고 함수 여러 개 만드는 데 익숙해지기

거리, 시간

def getDistance(s, h, m):
    return s * (h + m/60)     #distance = speed * (hour + minute / 60)

def getTime(s, d):
    hour = int(d//s)                #h = int(time)
    min = int((d/s - d//s) * 60)
    print(f'time: {d/s}')
    return hour, min

팩토리얼 재귀함수

def factorial(num):
    if num == 1:
        return 1
    else:
        return num * factorial(num-1)
        
n = int(input('input number: '))
print(format(factorial(n),','))

등차수열

def calculate(a1, add, n):
    total = 0
    for i in range(n):
        total += a1 +add*i
        print(f'{i+1} 번째 항의 값: {a1 + add*i}')
        print(f'{i+1}번째 항까지의 합: {total}')

a1 = int(input("a1 임력: "))
add = int(input("공차 입력: "))
n = int(input("n 입력: "))

등비수열

def calculate(a1, add, n):
    total = 0
    for i in range(n):
        total += a1 * pow(add, i)
        print(f'{i+1} 번째 항의 값: {a1 * pow(add, i)}')
        print(f'{i+1}번째 항까지의 합: {total}')

a1 = int(input("a1 임력: "))
add = int(input("공비 입력: "))
n = int(input("n 입력: "))

calculate(a1, add, n)

모듈

할인율 결정

  • 내 코드:
# buyDiscount.py
def rate(n):
    if n == 1:
        return 5
    elif n == 2:
        return 10
    elif n == 3:
        return 15
    elif n == 4:
        return 20
    elif n >= 5:
        return 25

def printTotal(price, rate):
    result = format(int(price * ((100-rate)/100)), ",")
    print(f'합계: {result}원')
import buyDiscount as buy
price = []
count = 0

while True:
    check = input("상품을 구매 하시겠어요? 1.구매 2.종료")
    if check == '2': break
    price.append(int(input('상품 가격 입력: ')))
    count += 1

print(f'할인률: {buy.rate(count)}')
buy.printTotal(sum(price), buy.rate(count))
  • 답안 코드:
#dicount.py
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:
        selectNumber = int(input('1.구매, 2.종료'))
        if selectNumber == 1:
            goods_price = int(input('상품 가격 입력: '))
            gs.append(goods_price)
        elif selectNumber == 2:
            result = dc.calculatorTotalPrice(gs)
            flag = False

    print(f'할인율: {result[0]}')
    print(f'합계: {dc.formatedNumber(result[1])}')

순열

#permutation.py
def gerPermutationCnt(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 입력: '))

print(f'{numN}P{numR}: {pt.gerPermutationCnt(numN, numR)}')
#pt.gerPermutationCnt(numN, numR, logPrint=False) 이면 print 출력 안됨

listVar = [1, 2, 3, 4, 5, 6, 7, 8]
rVar = 3
pt.getPermutations(listVar, rVar)
  • itertools 패키지

클래스

회원가입

#member.py
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):
        isMemeber = i in self.members
        if isMemeber 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]}')
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()

도서 관리 프로그램

내 코드:

book.py
class Book:
    def __init__(self, n, p, i):
        self.name = n
        self.price = p
        self.isbn = i

class BookRepository:
    def __init__(self):
        self.bDic = {}

    def registBook(self, b):
        self.bDic[b.name] = [b.price, b.isbn]

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

    def printBooksInfo(self):
        for bk in self.bDic.keys():
            print(f'name: {bk}')
            print(f'price: {self.bDic[bk][0]}')
            print(f'isbn: {self.bDic[bk][1]}\n')


    def printBookInfo(self, t):
        isTitle = t in self.bDic
        if isTitle:
            print(f'name: {t}')
            print(f'price: {self.bDic.get(t)[0]}')
            print(f'isbn: {self.bDic.get(t)[1]}\n')
        else:
            print('그런 책은 없음')   #그런 책은 없음!
import book as bk

books = bk.BookRepository()

for i in range(2):
    bName = input("book name: ")
    bPrice = input('book price: ')
    bIsbn = input('book isbn: ')

    b = bk.Book(bName, bPrice, bIsbn)
    books.registBook(b)

books.printBooksInfo()
books.printBookInfo('어린왕자')

강의:

#book2.py
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 book2 as bk

myBRepository = bk.BookRepository()

myBRepository.registBook(bk.Book('python', '20000', '123456789'))
myBRepository.registBook(bk.Book('java', '25000', '46545645'))
myBRepository.registBook(bk.Book('c/c++', '27000', '7546468'))

myBRepository.printBooksInfo()
myBRepository.printBookInfo('123456789')

주사위 게임

내 코드:

#dice.py
import random

class Dice:
    def __init__(self):
        pass
    def setCnum(self):
        print('[Dice] setCnum()')
        global cnum
        cnum = random.randint(1, 6)
        #print(f'cnum = {cnum}')

    def setUnum(self):
        print('[Dice] setUnum()')
        global unum
        unum = random.randint(1, 6)
        #print(f'unum = {unum}')

    def startGame(self):
        print('[Dice] startGame()')

    def printResult(self):
        print('[Dice] printResult')
        if cnum > unum:
            print(f'컴퓨터 vs 유저 : {cnum} vs {unum} >> 컴퓨터 승!!')
        elif cnum < unum:
            print(f'컴퓨터 vs 유저 : {cnum} vs {unum} >> 유저 승!!')
        elif cnum == unum:
            print(f'컴퓨터 vs 유저 : {cnum} vs {unum} >> 무승부!!')
import dice as dc

game1 = dc.Dice()
game1.setCnum()
game1.setUnum()
game1.startGame()
game1.printResult()

gpt에게 물어본 결과 이 경우 global variable을 쓰면 예상치 못한 결과(가독성 별로.. 어디서든 수정 가능 등등)가 나올 수 있기 때문에 추천하지 않는다고 한다. gpt가 추천한 코드(강의 정답 코드랑 비슷):

class Dice:
    def __init__(self):
        self.cnum = None
        self.unum = None

강의:

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} >> 유저 승!!')
            if self.cNum == self.uNum:
                print(f'컴퓨터 vs 유저: {self.cNum} vs {self.uNum} >> 무승부!!')
import dice2

dc = dice2.Dice()
dc.startGame()
dc.printResult()

사전

# ADictionary.py
from abc import ABCMeta
from abc import abstractmethod

class AbsDictionary(metaclass=ABCMeta):

    def __init__(self):
        self.wordDic = {}

    @abstractmethod
    def registWord(self, w1, w2):   # 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 KorToJpa(AbsDictionary):
    def __init__(self):
        super().__init__()

    def registWord(self, w1, w2):
        print(f'[KorToJpa] registWord(): {w1} to {w2}')
        self.wordDic[w1] = w2

    def removeWord(self, w1):
        print(f'[KorToJpa] removeWord(): {w1}')
        del self.wordDic[w1]

    def updateWord(self, w1, w2):
        print(f'[KorToJpa] updateWord(): {w1} to {w2}')
        self.wordDic[w1] = w2

    def searchWord(self, w1):
        print(f'[KorToJpa] 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.printWords()

kTe.updateWord('책', 'book')

kTe.printWords()

>>>
[KorToEng] registWord(): 책 to bok
[KorToEng] registWord(): 나비 to butterfly

책: bok
나비: butterfly

[KorToEng] updateWord(): 책 to book

책: book
나비: butterfly

자동차 경주

# car.py
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.py
from time import sleep

class CarRacing:
    def __init__(self):
        self.cars = []
        self.rankings = []

    def startRacing(self):
        for i in range(10):  #10바퀴
            print(f'Racing: {i+1}바퀴')
            for car in self.cars:
                car.distance += car.getDistanceForHour()

            sleep(1)  #프로그램 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_games import racing as rc
from car_games import car

myCarGame = rc.CarRacing()
car01 = car.Car('Car01', 'White', 250)
car02 = car.Car('Car02', 'Black', 300)
car03 = car.Car('Car03', 'Navy', 270)

myCarGame.addCar(car01)
myCarGame.addCar(car02)
myCarGame.addCar(car03)

myCarGame.startRacing()

>>>
Racing: 1바퀴
Car01: 18		Car02: 4		Car03: 109		
Racing: 2바퀴
Car01: 95		Car02: 295		Car03: 167	
...
Racing: 10바퀴
Car01: 1223		Car02: 1443		Car03: 1150	

mp3 플레이어

내 코드:

#player.py
import random
from time import sleep

class Player:

    def __init__(self):
        self.songList = []
        self.isLoop = False

    def addSong(self, s):
        self.songList.append(s)

    def play(self):
        for song in self.songList:
            print(f'{song.title} playing...')
            sleep(1)

    def shuffle(self):
        newList = []

        while self.songList:  # self.songList = []이면 false
            randNum = random.randint(0, len(self.songList)-1)   
            newList.append(self.songList.pop(randNum))

        self.songList = newList



    def setIsLoop(self, flag): # 뭔지 모르겠어서 pass
        pass
#song.py
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}')
import song as sg
import player as pl

s1 = sg.Song('Last Nite', 'The Strokes', "3:14")
s2 = sg.Song('tystnar i luren', 'Miriam Bryant, Victor Leksell', '3:14')
s3 = sg.Song('Karma Police', 'Radiohead', '4:24')
s4 = sg.Song('I AM', 'IVE', '3:04')
s5 = sg.Song('Smells Like Teen Spirit', 'Nirvana', '5:02')


s1.printSongInfo()
s2.printSongInfo()
s3.printSongInfo()
s4.printSongInfo()
s5.printSongInfo()

pl1 = pl.Player()

pl1.addSong(s1)
pl1.addSong(s2)
pl1.addSong(s3)
pl1.addSong(s4)
pl1.addSong(s5)

pl1.play()
print('\n')

pl1.shuffle()
pl1.play()

강의:

# mp3player.py
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 shuffle(self):
        random.shuffle(self.songList)

    def setIsLoop(self, flag):
        self.isLoop = flag
import mp3player as mp3

s1 = mp3.Song('신호등', '이무진', 3)
s2 = mp3.Song('tystnar i luren', 'Miriam Bryant, Victor Leksell', 3)
s3 = mp3.Song('Karma Police', 'Radiohead', 2)

player = mp3.Player()
player.addSong(s1)
player.addSong(s2)
player.addSong(s3)

player.setIsLoop(False)
player.shuffle()
player.play()
  • random.shuffle(listname): 리스트 섞기

예외 처리

계산기

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

소수인 난수 생성

# prime_module.py
class NotPrimeException(Exception):
    def __init__(self, n):
        super().__init__(f'{n} is not a prime number.')

class PrimeException(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 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}')

총 구매 금액

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)
# calculatorPurchase.py
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]   #globals(): 위에 있는 g1Price~ 변수 참조가능

    print('--------------------------------------------')
    print(f'총 구매 금액: {formatedNumber(totalPrice)}원')
    print('------------------미결제 항목------------------')
    for g in againCntInput.keys():
        print(f'상품: {g}, \t 구매 개수: {againCntInput[g]}')
    print('--------------------------------------------')
  • globals()[]: 전역 변수 생성 / 사용

회원가입

import member as 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)
    mem.RegistMember(m_name, m_mail, m_pw, m_addr, m_phone)
except mem.EmptyDataException as e:
    print(e)
# 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}')

은행 계좌

내 코드:

import account as ac

name = input('통장 개설을 위한 예금주 입력: ')

b1 = ac.Bank(name)

b1.printBankInfo()

while 1:

    num = int(input('1.입금, 2.출금, 3.종료'))
    if num == 1:
        dMon = int(input('입금액 입력: '))
        b1.deposit(dMon)
        b1.printBankInfo()

    elif num == 2:
        wMon = int(input('출금액 입력: '))
        try:
            b1.withdraw(wMon)
        except Exception as e:
            print(e)
        else:
            b1.printBankInfo()

    elif num == 3:
        print('bye~')
        break
# account.py
import random

class NoMoney(Exception):
    def __init__(self, left, wd):
        super().__init__(f"잔고부족!!, 잔액: {left}, 출금액: {wd}")

class Bank:
    def __init__(self, name):
        self.name = name
        self.num = random.randint(10000, 99999)
        self.money = 0

    def printBankInfo(self):
        print('-' * 30)
        print(f'account_name: {self.name}')
        print(f'account_no: {self.num}')
        print(f'totalMoney: {self.money}원')
        print('-' * 30)

    def deposit(self, dMon):
        self.money += dMon

    def withdraw(self, wMon):
        if (self.money - wMon) < 0:
            raise NoMoney(self.money, wMon)
        else:
            self.money -= wMon

강의:

import bank

koreaBank = bank.Bank()      # 은행이름: 한국은행

new_account_name = input('통장 개설을 위한 예금주 입력: ')
myAccount = bank.PrivateBank(koreaBank, new_account_name)
myAccount.printBankInfo()

while True:

    selectNumber = int(input('1.입금, 2.출금, 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
# 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, 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}')

else: 예외가 발생하지 않으면 실행.
finally: 예외가 발생과 상관없이 항상 실햄.

정답 코드에서는 except Exception as e 대신 except ac.NoMoney as e 사용. 정확한 오류 처리를 위해 이렇게 특정 오류의 이름을 명시하는 것이 좋다. 코드의 명확성을 향상시키고, 예외가 발생했을 때 무엇이 잘못되었는지 이해하기 쉽기 때문이다. (chat gpt한테 물어봄)

텍스트파일

다이어리 프로그램

import diary

members = {}
uri = '/Users/이름/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'
            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')
            printMembers()

    elif selectNum == 4:
        print('Bye~')
        break
# 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

수학

약수와 소수

import random

rNum = random.randint(100, 1000)
print(f'rNum: {rNum}')

for num in range(1, rNum):

    soinsuFlag = 0  # 소인수: 약수이면서 소수

    # 약수
    if rNum % num == 0:
        print(f'[약수]: {num}')
        soinsuFlag += 1

    # 소수
    if num != 1:
        flag = True
        for n in range(2, num):
            if num % n == 0:
                flag = False
                break

        if(flag):
            print(f'[소수]: {num}')
            soinsuFlag += 1

    if soinsuFlag >= 2:
        print(f'[소인수]: {num}')

확률

def proFun():
    numN = int(input('numN 입력: '))  # 전체
    numR = int(input('numR 입력: '))  # 특정 경우

    resultP = 1
    resultR = 1
    resultC = 1

    #순열(P)
    for n in range(numN, (numN - numR), -1):
        resultP = resultP * n
    print("resultP: {}".format(resultP))

    #R(f)
    for n in range(numR, 0, -1):
        resultR = resultR * n
    print("resultR: {}".format(resultR))

    #조합(C)
    resultC = int(resultP / resultR)
    print("resultC: {}".format(resultC))

    return resultC

sample = proFun()
print(f'sample: {sample}')

event1 = proFun()
print(f'sevent1: {event1}')   # 꽝

event2 = proFun()
print(f'event2: {event2}')    # 선물

probability = (event1 * event2) / sample
print(f'probability: {round(probability * 100, 2)}')

0개의 댓글