스터디노트(Python 중급5~7)

zoe·2023년 3월 9일
0

객체와 매모리

  • 변수는 객체의 메모리 주소를 저장하고 이를 이용해서 객체를 참조
class Robot:
    def __init__(self, color, height, weight):
        self.color = color
        self.height = height
        self.weight = weight

    def printRobotInfo(self):
        print(f'color : {self.color}')
        print(f'height : {self.height}')
        print('weight : {}'.format(self.weight))


rb1 = Robot('red', 200, 80)
rb2 = Robot('blue', 300, 120)
rb3 = rb1 #rb3의 rb1의 메모리 주소값이 할당됨, 메모리 주소가 복사된 것

rb1.printRobotInfo()
rb2.printRobotInfo()
rb3.printRobotInfo()
print()
rb1.color = 'gray'
rb1.height = 250
rb1.weight = 100

rb1.printRobotInfo()
rb2.printRobotInfo()
rb3.printRobotInfo()
  • 실습

💡 국어, 영어, 수학 점수를 입력받아 리스트에 저장하고 원본을 유지한 상태로, 복사본을 만들어 과목별 점수를 10% 올렸을 경우에 평균을 출력

  • 💡 enumerate() : 리스트 안의 각각의 값에 순서(인덱스)를 부여
# 국어, 영어, 수학 점수를 입력받아 리스트에 저장하고 원본을 유지한 상태로,
# 복사본을 만들어 과목별 점수를 10% 올렸을 경우에 평균을 출력

scores = [int(input('국어 점수 입력 : ')),
          int(input('영어 점수 입력 : ')),
          int(input('수학 점수 입력 : '))]

print(scores)

copyScores = scores.copy() # copyScores라는 새로운 변수에 scores 값들이 복사된 것

for idx, score in enumerate(copyScores): # enumerate() : 리스트 안의 각각의 값에 순서(인덱스)를 부여
    result = score * 1.1
    copyScores[idx] = 100 if score > 100 else result # ★

print('이전 평균 : {}' .format(sum(scores) / len(scores)))
print(f'이후 평균 : {sum(copyScores) / len(copyScores)}')

💡 얕은 복사와 깊은 복사

  • 얕은 복사 : 객체 주소를 복사하는 것으로 객체 자체가 복사되지 않는다 (메모리 주소만 복사)

  • 깊은 복사 : 객체 자체를 복사하는 것으로 또 하나의 객체가 만들어진다

  • 💡 extend() : 가장 바깥쪽 iterable을 넣음, 주소 값이 변하지 않고 유지됨 (출처 : extend() 정보 출처)

  • 💡 copy() : copy모듈을 불러와서 사용 가능(import copy)

  • sort() : 리스트의 항목들을 제자리에서 정렬합니다 (출처 : sort() 정보 출처)

  • 💡 pop() : 리스트에서 주어진 위치에 있는 항목을 삭제하고, 그 항목을 돌려줌. 인덱스를 지정하지 않으면, a.pop() 은 리스트의 마지막 항목을 삭제 (출처 : pop() 정보 출처)

# 얕은 복사
class TemCls:
    def __init__(self, n, s):
        self.number = n
        self.str = s

    def printClsInfo(self):
        print(f'self.number : {self.number}')
        print(f'self.str : {self.str}')

tc1 = TemCls(10, 'hello')
tc2 = tc1

tc1.printClsInfo()
tc2.printClsInfo()

tc2.number = 3.14
tc2.str = 'bye'

tc1.printClsInfo()
tc2.printClsInfo()
# 깊은 복사

import copy

tc1 = TemCls(10, 'hello')
tc2 = copy.copy(tc1)

tc1.printClsInfo()
tc2.printClsInfo()

tc2.number = 3.14
tc2.str = 'bye'

tc1.printClsInfo()
tc2.printClsInfo()
import copy

scores = [9,8,5,7,6,10]
scoresCopy = []
scoresCopy2 = []
scoresCopy3 = []
scoresCopy4 = []
scoresCopy5 = []

scoresCopy = scores
print(f'id(scores) : {id(scores)}')
print(f'id(scoresCopy) : {id(scoresCopy)}')

for s in scoresCopy2:
    scores.append(s)

print(f'id(scores) : {id(scores)}')
print(f'id(scoresCopy) : {id(scoresCopy2)}')

scoresCopy3.extend(scores)
# 출처 :  https://velog.io/@cha-suyeon/Python-%EB%A6%AC%EC%8A%A4%ED%8A%B8%EC%9D%98-%EB%8D%94%ED%95%98%EA%B8%B0-extendappend-%EC%B0%A8%EC%9D%B4-%EC%A0%90%ED%94%84%ED%88%AC%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%A2%85%ED%95%A9%EB%AC%B8%EC%A0%9C-3%EB%B2%88
# 가장 바깥쪽 iterable을 넣음
# 주소 값이 변하지 않고 유지됨
print(f'id(scores) : {id(scores)}')
print(f'id(scoresCopy) : {id(scoresCopy3)}')

scoresCopy4 = scores.copy()
print(f'id(scores) : {id(scores)}')
print(f'id(scoresCopy) : {id(scoresCopy4)}')

scoresCopy5 = scores[:]
# scores[:] 슬라이싱을 이용하여 전체를 자름(?)
# 출처 : https://dojang.io/mod/page/view.php?id=2208
print(f'id(scores) : {id(scores)}')
print(f'id(scoresCopy) : {id(scoresCopy4)}')
  • 실습

💡 선수의 원본 점수를 이용해서 평균을 출력하고, 최고값과 최저값을 제외한 평균을 출력하는 프로그램을 생성

# 선수의 원본 점수를 이용해서 평균을 출력하고, 최고값과 최저값을 제외한 평균을 출력하는 프로그램을 생성

plaOriSco = [8.7, 9.1, 8.9, 9.0, 7.9, 9.5, 8.8, 8.3]
plaCopSco = plaOriSco.copy()

plaOriSco.sort()
# sort() : 정렬, 오름차순
# 출처 : https://docs.python.org/ko/3/tutorial/datastructures.html
print(plaOriSco)

plaCopSco.sort()
plaCopSco.pop(0)
plaCopSco.pop()
# pop() : 리스트에서 주어진 위치에 있는 항목을 삭제하고, 그 항목을 돌려줌. 인덱스를 지정하지 않으면, a.pop() 은 리스트의 마지막 항목을 삭제
# 출처 : https://docs.python.org/ko/3/tutorial/datastructures.html
print('plaOriSco : {}' .format(plaOriSco))
print(f'plaCopSco : {plaCopSco}')

oriTot = round(sum(plaOriSco),2)
oriAvg = round(oriTot / len(plaOriSco),2)
print('Original Total : {}' .format(oriTot))
print('Original Average : {}' .format(oriAvg))

copTot = round(sum(plaCopSco),2)
copAvg = round(oriTot / len(plaCopSco),2)
print('Original Total : {}' .format(copTot))
print('Original Average : {}' .format(copAvg))

print(f'oriAvg - copAvg : {oriAvg - copAvg}')

💡 클래스 상속

  • 클래스는 또 다른 클래스를 상속해서 내 것처럼 사용할 수 있다
class NormalCar:

    def drive(self):
        print('[NormalCar] drive() called!!')

    def back(self):
        print('[NormalCar] back() called!!')


class TurboCar(NormalCar): # ★

    def torbo(self):
        print('[TurboCar] turbo() called!!')


myTurboCar = TurboCar()
myTurboCar.drive()
myTurboCar.back()
myTurboCar.torbo()
  • 실습

덧셈, 뺄셈 기능이 있는 클래스를 만들고, 이를 상속하는 클래스를 만들어서 곱셈과 나눔셈 기능을 추가

# 덧셈, 뺄셈 기능이 있는 클래스를 만들고, 이를 상속하는 클래스를 만들어서 곱셈과 나눔셈 기능을 추가

class CalculatorSuper:

    def add(self, n1, n2):
        return n1 + n2

    def sub(self, n1, n2):
        return  n1 - n2


class CalculatorChild(CalculatorSuper):

    def mul(self, n1, n2):
        return n1 * n2

    def div(self, n1, n2):
        return n1 / n2


cal = CalculatorChild()
print(f'cal.add(10, 20) : {cal.add(10,20)}')
print(f'cal.sub(10, 20) : {cal.sub(10,20)}')
print(f'cal.mul(10, 20) : {cal.mul(10,20)}')
print(f'cal.div(10, 20) : {cal.div(10,20)}')

💡 생성자

  • 객체가 생성될 때 생성자를 호출하면 init()가 자동 호출된다
  • init()가 속성을 초기화
  • 💡 상위 클래스의 속성을 초기화하기 위해서 super()를 이용
class Calculator:
    def __init__(self):
        print('[Calculator] __init() called!!')

cal = Calculator() # 메소드를 호출하면 __init__() 메소드도 같이 호출됨
class Calculator:
    def __init__(self, n1, n2):
        print('[Calculator] __init() called!!')
        self.num1 = n1
        self.num2 = n2

cal = Calculator(10,20) # 메소드를 호출하면 __init__() 메소드도 같이 호출됨
print(f'cal.num1 : {cal.num1}')
print(f'cal.num2 : {cal.num2}')
class Calculator2:
    def __init__(self):
        print('[Calculator] __init() called!!')
        self.num1 = 10
        self.num2 = 100

cal = Calculator2() # 항상 10, 100으로 num1, num2의 값이 초기화됨
print(f'cal.num1 : {cal.num1}')
print(f'cal.num2 : {cal.num2}')
class Calculator3:
    def __init__(self, n):
        print('[Calculator] __init() called!!')
        self.num1 = n
        self.num2 = 100

cal = Calculator3(3.14)
print(f'cal.num1 : {cal.num1}')
print(f'cal.num2 : {cal.num2}')
  • super()
class P_class:

    def __init__(self, pNum1, pNum2):
        print('[pClass] __init__()')

        self.pNum1 = pNum1
        self.pNum2 = pNum2


class C_Class(P_class):

    def __init__(self,cNum1, cNum2):
        print('[cClass] __init__()')

        P_class.__init__(self, cNum1, cNum2)
        # 여기서 상속 클래스의 __init__() 메소드 강제로 불러오는 것은 가능
        # pNum1 = cNum1, pNum2 = cNum2 할당

        self.cNum1 = cNum1
        self.cNum2 = cNum2

cls = C_Class(10,20)
class P_class:

    def __init__(self, pNum1, pNum2):
        print('[pClass] __init__()')

        self.pNum1 = pNum1
        self.pNum2 = pNum2
        
        
class C_Class2(P_class):

    def __init__(self,cNum1, cNum2):
        print('[cClass] __init__()')

        super().__init__(cNum1, cNum2)
        # super()를 이용하면 상속 클래스의 __init__() 메소드를 불러올 수 있음

        self.cNum1 = cNum1
        self.cNum2 = cNum2

cls = C_Class(10,20)
  • 실습

💡 중간고사 클래스와 기말고사 클래스를 상속관계로 만들고 각각의 점수를 초기화하자.
또한 총점 및 평균을 반환하는 기능도 생성

# 중간고사 클래스와 기말고사 클래스를 상속관계로 만들고 각각의 점수를 초기화하자.
# 또한 총점 및 평균을 반환하는 기능도 생성

class MidExam:

    def __init__(self, kor, eng, mat):
        print('[MidExam] __init__()')

        self.mid_kor_score = kor
        self.mid_eng_score = eng
        self.mid_mat_score = mat

    def printScore(self):
        print(f'mid_kor_score : {self.mid_kor_score}')
        print(f'mid_eng_score : {self.mid_eng_score}')
        print(f'mid_mat_score : {self.mid_eng_score}')

class EndExam(MidExam):

    def __init__(self, mid_kor, mid_eng, mid_mat, end_kor, end_eng, end_mat):
        print('[EndExam] __init__()')

        super().__init__(mid_kor, mid_eng, mid_mat) # ★

        self.end_kor_score = end_kor
        self.end_eng_score = end_eng
        self.end_mat_score = end_mat

    def printScore(self):

        super().printScore() # ★

        print(f'end_kor_score : {self.end_kor_score}')
        print(f'end_eng_score : {self.end_eng_score}')
        print(f'end_mat_score : {self.end_eng_score}')

    def getTotalScore(self):
        total = self.mid_kor_score + self.mid_eng_score + self.mid_mat_score \
        + self.end_kor_score + self.end_eng_score + self.end_mat_score

        return total

    def getAverageScore(self):
        return self.getTotalScore() / 6


exam = EndExam(85, 90, 88, 75, 85, 95)
exam.printScore()

print(f'Total : {exam.getTotalScore()}')
print(f'Average : {round(exam.getAverageScore(),2)}')

다중 상속

  • 2개 이상의 클래스를 상속한다

💡 BasicCalculator와 DeveloperCalculator 클래스를 다음과 같이 만들고 이들 클래스를 상속해서 Calculator 클래스를 만들고 사용

# BasicCalculator와 DeveloperCalculator 클래스를 다음과 같이 만들고
# 이들 클래스를 상속해서 Calculator 클래스를 만들고 사용

class BasicCalculator:
    def add(self, n1, n2):
        return n1 + n2

    def sub(self, n1, n2):
        return n1 - n2

    def mul(self, n1, n2):
        return n1 * n2

    def div(self, n1, n2):
        return n1 / n2


class DeveloperCalculator:
    def mod(self, n1, n2):
        return n1 % n2

    def flo(self, n1, n2):
        return n1 // n2

    def exp(self, n1, n2):
        return n1 ** n2


class NewCalculator(BasicCalculator, DeveloperCalculator):
    def __init__(self): # ★
        pass


cal = NewCalculator()
print(f'cal.add(10, 20) : {cal.add(10, 20)}')
print(f'cal.sub(10, 20) : {cal.sub(10, 20)}')
print(f'cal.mul(10, 20) : {cal.mul(10, 20)}')
print(f'cal.div(10, 20) : {cal.div(10, 20)}')

print(f'cal.mod(10, 20) : {cal.mod(10, 20)}')
print(f'cal.flo(10, 20) : {cal.div(10, 20)}')
print(f'cal.exp(10, 20) : {cal.exp(2, 5)}')

💡 오버라이딩

  • 하위 클래스에서 상위 클래스의 매서드를 재정의한다
class Robot:

    def __init__(self, c, h, w):
        self.color = c
        self.height = h
        self.weight = w

    def fire(self):
        print('총알발사!!')

    def printRobotInfo(self):
        print('self.color : {}' .format(self.color))
        print('self.height : {}'.format(self.height))
        print(f'self.weight : {self.weight}')


class NewRobot(Robot):

    def __init__(self, c, h, w):
        super().__init__(c, h, w) # ★★★

    def fire(self):
        #super().fire()
        print('레이저 발사!!')



myRobot = NewRobot('red', 200, 300)
myRobot.printRobotInfo()
myRobot.fire()
  • 실습

💡 삼각형 넓이를 계산하는 클래스를 만들고 이를 상속하는 클래스에서 getArea()를 오버라이딩 해서 출력 결과가 다음과 같을 수 있도록 클래스를 생성

#삼각형 넓이를 계산하는 클래스를 만들고 이를 상속하는 클래스에서 getArea()를
# 오버라이딩 해서 출력 결과가 다음과 같을 수 있도록 클래스를 생성

class TriangleArea:

    def __init__(self, w, h):
        self.width = w
        self.height = h

    def printTriangleAreaInfo(self):
        print(f'width : {self.width}')
        print(f'height : {self.height}')

    def getArea(self):
        return self.width * self.height / 2


class NewTriangleArea(TriangleArea):

    def __init__(self, w, h):
        super().__init__(w, h)

    def getArea(self):
        return str(self.width * self.height / 2) + '㎠'

ta = NewTriangleArea(7,5)
ta.printTriangleAreaInfo()
triangleArea = ta.getArea()
print(f'TriangleArea : {triangleArea}')

💡 추상클래스

  • 상위 클래스에서 하위 클래스에 메서드 구현을 강요한다(※ 공통 기능을 사용하되, 실행되는 구문이나 기능(?)을 각각 다르게 구현하고자 할 때 사용)
  • 구현하지 않으면 에러가 남
  • 💡
    from abc import ABCMeta
    from abc import abstractmethod
    metaclass=ABCMeta
    @abstractmethod
from abc import ABCMeta
from abc import abstractmethod

class AirPlane(metaclass=ABCMeta):

    @abstractmethod
    def flight(self):
        pass

    def forward(self):
        print('전진!')

    def backward(self):
        print('후진!')


class Airliner(AirPlane):

    def __init__(self, c):
        self.color = c

    def flight(self):
        print('시속 400km/h 비행!')


class flightPlane(AirPlane):
    def __init__(self,c):
        self.color = c

    def flight(self):
        print('시속 700km/h 비행!')


al = Airliner('red')
al.forward()
al.backward()
al.flight()


fl = flightPlane('blue')
fl.forward()
fl.backward()
fl.flight()
  • 실습

계산기 추상 클래스를 만들고 이를 이용해서 새로운 계산기 클래스를 만들어 보자. 추상 클래스에는 덧셈, 뺄셈, 곱셈, 나눗셈 기능이 선언되어 있어야 함

# 계산기 추상 클래스를 만들고 이를 이용해서 새로운 계산기 클래스를 만들어 보자.
# 추상 클래스에는 덧셈, 뺄셈, 곱셈, 나눗셈 기능이 선언되어 있어야 함

from abc import ABCMeta
from abc import abstractmethod

class Calculator(metaclass=ABCMeta):

    @abstractmethod
    def add(self, n1, n2):
        pass

    @abstractmethod
    def sub(self, n1, n2):
        pass

    @abstractmethod
    def mul(self, n1, n2):
        pass

    @abstractmethod
    def div(self, n1, n2):
        pass


class DeveloperCalculator(Calculator):

    def add(self, n1, n2):
        return n1 + n2

    def sub(self, n1, n2):
        return n1 - n2

    def mul(self, n1, n2):
        return n1 * n2

    def div(self, n1, n2):
        return n1 * n2

    def mod(self, n1, n2):
        return n1 % n2

    def flo(self, n1, n2):
        return n1 // n2

cal1 = DeveloperCalculator()
print(f'cal1.add(10, 20) : {cal1.add(10, 20)}')
print(f'cal1.sub(10, 20) : {cal1.sub(10, 20)}')
print(f'cal1.mul(10, 20) : {cal1.mul(10, 20)}')
print(f'cal1.div(10, 20) : {cal1.div(10, 20)}')
print(f'cal1.mod(10, 20) : {cal1.mod(10, 20)}')
print(f'cal1.flo(10, 20) : {cal1.flo(10, 20)}')

예외란?

  • 예외 : 문법적인 문제는 없으나 실행 중 발생하는 예상하지 못한 문제
  • 💡 예외 관련 클래스는 Exception 클래스를 상속한다
def add(n1, n2):
    print(n1 + n2)

def sub(n1, n2):
    print(n1 - n2)

def mul(n1, n2):
    print(n1 * n2)

def div(n1, n2):
    print(n1 / n2)

# 10, 0을 입력할 경우
firstNum = int(input('first number : '))
secondNum = int(input('second number : '))

add(firstNum, secondNum)
sub(firstNum, secondNum)
mul(firstNum, secondNum)
div(firstNum, secondNum) # 0으로 나눌 수 없어 에러 발생
print(int('hello'))

lists = [1, 2, 3, 4, 5, 6]
print(lists[6])

예외처리

  • 예상하지 못한 예외가 프로그램 전체에 영향이 없도록 처리함
  • 발생한 예외에 대해서는 별도 처리가 필요할 수 있음
  • 💡 예외 발생 예상 구문을 try ~ except로 감싼다(※문제가 발생하지 않은 경우 정상 실행, 문제가 발생한 경우 except문 실행 후 다음 내용 실행)
n1 = 10; n2 = 0

try:
    print(n1 / n2)
except:
    print('예상치 못한 예외가 발생했습니다.')
    print('다른 프로그램 실행에는 문제가 없습니다.')
print(n1 * n2)
print(n1 - n2)
print(n1 + n2)
  • 실습

💡 사용자로부터 숫자 5개를 입력받을 때 숫자가 아닌 자료형이 입력되면 예외 처리하는 프로그램을 생성

# 사용자로부터 숫자 5개를 입력받을 때 숫자가 아닌 자료형이 입력되면 예외 처리하는 프로그램을 생성

nums = []

n = 1
while n < 6 :
    try:
        num = int(input('input number : '))
    except:
        print('예외 발생!')
        continue # 예외가 발생했을 때 밑에 구문을 실행하지 않고 다음 while 문을 계속해서 진행하기 위해 ★

    nums.append(num)
    n += 1

print(f'nums : {nums}')

💡 try ~ except ~ else

  • 💡 try ~ except ~ else : 예외가 발생하지 않은 경우 실행하는 구문, else 생략 가능
nums = []
n = 1

while n < 6:

    try:
        num = int(input('input number : '))

    except:
        print('예외 발생!')
        continue
    else:
        if num % 2 == 0:
            nums.append(num)
            n += 1
        else:
            print('입력한 숫자는 홀수 입니다.', end='')
            print('다시 입력 하세요')
            continue # ★★★★★
  • 실습

사용자로부터 숫자 5개를 입력받아 짝수, 홀수, 실수로 구분해서 각각을 리스트에 저장하는 프로그램을 생성

# 사용자로부터 숫자 5개를 입력받아 짝수, 홀수, 실수로 구분해서 각각을 리스트에 저장하는 프로그램을 생성

eveList = []; oddList = []; floatList = []

n = 1

while n < 6 :

    try :
        num = float(input('input number : '))

    except:
        print('exception raise!')
        print('input number again!')
        continue

    else:
        if num - int(num) == 0:
            if num % 2 == 0 :
                eveList.append(int(num))
            else :
                oddList.append(int(num))
        else:
            floatList.append(num)
        n += 1

print('eveList : {}' .format(eveList))
print(f'oddList : {oddList}')
print(f'floatList : {floatList}')

💡 finally

  • finally : 예외 발생과 상관없이 항상 실행
try:
    inputData = input('input number : ')
    numInt = int(inputData)
except:
    print('exception raise!!')
    print('not number!!')
    numInt = 0
else:
    if numInt % 2 == 0:
        print('inputData is even number!!')
    else:
        print('inputData is odd number!!')
finally:
    print(f'inputData : {inputData}')
  • 실습

💡 사용자로부터 숫자 5개를 입력받아 짝수, 홀수, 실수와 입력한 모든 데이터를 각각 출력하는 프로그램을 생성

# 사용자로부터 숫자 5개를 입력받아 짝수, 홀수, 실수와 입력한 모든 데이터를
# 각각 출력하는 프로그램을 생성

eveList = []; oddList = []; floatList = []; dataList = []

n = 1
while n < 6:
    try:
        data = input('input number : ')
        inputData = float(data)
    except:
        print('exception raise!!')
        print('input number again!!')
        continue

    else:
        if inputData - int(inputData) == 0:
            if inputData % 2 == 0:
                print('even number!')
                eveList.append(int(inputData))
            else:
                print('odd number!')
                oddList.append(int(inputData))

        else:
            print('float number!')
            floatList.append(inputData)

        n += 1 # 5개의 실수만 분류되기 위해서!
    finally:
        dataList.append(data) # 입력 받은 문자열도 포함하기 위해서!

print(f'eveList : {eveList}')
print(f'oddList : {oddList}')
print(f'floatList : {floatList}')
print('dataList : {}' .format(dataList))

💡 Exception 클래스

  • 💡 Exception 클래스 : 예외를 담당
  • (※ Exception을 사용하고 print()에서 출력하면 예외가 발생한 사유(어떤 에러인지)를 알 수 있음)
  • 💡 raise 키워드를 이용하면 예외를 발생시킬 수 있음
# num1 = 10, num2 = 0 입력
num1 = int(input('input number1 : '))
num2 = int(input('input number2 : '))

try:
    print(f'num1 / num2 = {num1 / num2}')
except Exception as e: # ★★★
	print('0으로 나룰 수 없습니다.')
    print(f'Exception : {e}') # 예외가 발생한 사유를 알 수 있음 ★★★

print(f'num1 * num2 = {num1 * num2}')
print(f'num1 - num2 = {num1 - num2}')
print(f'num1 + num2 = {num1 + num2}')
def divCalculator(n1, n2):

    if n2 != 0:
        print(f'{n1} / {n2} = {n1 / n2}')
    else:
        raise Exception('0으로 나눌 수 없습니다.')

num1 = int(input('input number1 : '))
num2 = int(input('input number2 : '))

try:
    divCalculator(num1, num2)
except Exception as e :
    print(f'Exception : {e}')
  • 실습

💡 사용자가 문자 메시지를 보낼때 10글자 이하면 SMS로 발송하고, 10글자를 초과하면 MMS로 발송하는 프로그램을 예외처리를 이용해서 생성

# 사용자가 문자 메시지를 보낼때 10글자 이하면 SMS로 발송하고, 10글자를
# 초과하면 MMS로 발송하는 프로그램을 예외처리를 이용해서 생성


def sendSMS(msg):
    if len(msg) > 10:
        raise Exception('길이 초과!! MMS 전환 후 발송!!', 1)

    else:
        print('SMS 발송!')

def sendMMS(msg):
    if len(msg) < 10:
        raise Exception('길이 미달!! SMS 전환 후 발송!!', 2)

    else:
        print('MMS 발송!')


msg = input('input massage : ')

try:
    sendSMS(msg)
except Exception as e:
    print(f'e : {e.args[0]}') # 길이 초과할 경우, 길이 초과!! MMS 전환 후 발송!! 메세지 나옴
    print(f'e : {e.args[1]}') # 1 에러 메세지 나옴

    if e.args[1] == 1: # 1 에러일 경우, sendMMS 함수 실행
        sendMMS(msg)
    elif e.args[1] == 2: # 2 에러일 경우, sendSMS 함수 실행
        sendMMS(msg)

💻 출처 : 제로베이스 데이터 취업 스쿨

profile
#데이터분석 #퍼포먼스마케팅 #데이터 #디지털마케팅

0개의 댓글