[2주차] 파이썬 중급 8~9

이철민·2023년 2월 10일

[오늘 배운 내용]

[예외]

  • 예외: 문법적인 문제는 없으나 실행 중 발생하는 예상하지 못한 문제.
def add(n1, n2):
    print(n1 + n2)

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

fn = int(input('input firstNum: '))
sn = int(input('input secondNum: '))

add(fn,sn)
div(fn,sn)

# 예외 예시
print(int('hello'))
print(3/0)

lists = [1, 2, 3, 4, 5, 6]
print(lists[5])
  • 예외 처리: 예외가 프로그램 전체 영향이 없도록 처리
  • try ~ escept: 예외 발생 구문을 try: ~ except: 로 감싼다.
# 사용자로부터 숫자 5개를 입력했을 때 숫자가 아닌 자료형이 입력되면 예외 처리하는 프로그램

nums = []
n = 1
while n < 6:

    try:
        num = int(input('input number: '))
    except:
        print('예외 발생!')
        continue

    nums.append(num)
    n += 1

print(f'nums: {nums}')
  • try ~ escept~ esle: 예외가 발생하지 않았을 때는 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

print(f'nums: {nums}')
  • finally: 예외 발생과 관계없이 항상 실행한다.
# 실습: 사용자로부터 숫자 5개를 입력받아 짝수, 홀수, 실수와 입력한 모든 데이터를 각각 출력하는 프로그램을 만들어보자.

evenList = []; oddList = []; floatList = []; dataList = []

n = 1
while n < 6:

    try:
        data = input('input number: ')
        floatNum = float(data)
    except:
        print('exception rise!')
        print('not number!')
        continue
    else:
        if floatNum - int(floatNum) != 0:
            print('float number!')
            floatList.append(floatNum)
        else:
            if floatNum % 2 == 0:
                print('even number!')
                evenList.append(floatNum)
            else:
                print('odd number!')
                oddList.append(floatNum)
        n += 1

    finally:
        dataList.append(data)      #에러가 뜨든 말든 사용자가 입력한 데이터를 모두 수집

print(f'evenList: {evenList}')
print(f'oddList: {oddList}')
print(f'floatList: {oddList}')
print(f'dataList: {dataList}')
  • exception 클래스: 예외 담당 클래스
num1 = int(input('input number1: '))
num2 = int(input('input number2: '))

try:
    print(f'num1/num2 = {num1 / num2}')
except Exception as e:
    print(f'exception: {e}')

print(f'num1*num2 = {num1 * num2}')
print(f'num1+num2 = {num1 + num2}')
print(f'num1-num2 = {num1 - num2}')
  • raise 키워드: 예외 강제 발생
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}')
  • 사용자 예외 클래스: Exception 클래스를 상속해서 사용자 예외 클래스를 만들 수 있다.
    • 사용자 예외 클래스는 반드시 Exception 클래스 상속
class NotUSeZeroException(Exception):

    def __init__(self, n):
        super().__init__(f'{n}은 사용할 수 없습니다.')

def divCalculator(n1,n2):

    if n2 == 0:
        raise NotUSeZeroException(n2)
    else:
        print(f'{n1}/{n2}: {n1/n2}')

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

try:
    divCalculator(num1, num2)
except NotUSeZeroException as e:
    print(e)
# 실습: 관리자 암호를 입력하고 다음 상태에 따라 예외 처리하는 예외 클래스를 만들어보자.

class PasswordLengthShortException(Exception):
    def __init__(self, str):
        super().__init__(f'{str}: 길이 5미만!')

class PasswordLengthLongException(Exception):
    def __init__(self, str):
        super().__init__(f'{str}: 길이 10초과!')

class PasswordWrongException(Exception):
    def __init__(self, str):
        super().__init__(f'{str}: 잘못된 비밀번호!')

adminPw = input('input admin password: ')

try:
    if len(adminPw) < 5:
        raise PasswordLengthShortException(adminPw)
    elif len(adminPw) > 10:
        raise PasswordLengthLongException(adminPw)
    elif adminPw != 'adminPw':
        raise PasswordWrongException(adminPw)
    elif adminPw == 'admin1234':
        print('빙고!')

except PasswordLengthShortException as e1:
    print(e1)
except PasswordLengthLongException as e2:
    print(e2)
except PasswordWrongException as e3:
    print(e3)

[텍스트 파일]

open() -> read() or write() -> close()

  • write()함수를 이용한 파일에 문자열 쓰기
file = open('/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt/test.txt', 'w')

strCnt= file.write('Hello python!')
print(f'strCnt: {strCnt}')

file.close()
예제) 
import time

lt = time.localtime()

# dateStr = '[' + str(lt.tm_year) + '년' + str(lt.tm_mon) + '월'+ str(lt.tm_mday) + '일]'

dateStr = '[' + time.strftime('%Y-%m-%d %H:%M:%S %p') + ']'

todaySchedule = input('오늘 일정: ')

file = open('/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt/test.txt', 'w')
file.write(dateStr + todaySchedule)
file.close()
  • read() 함수를 이용한 텍스트 파일 읽기
file = open('/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt/test.txt', 'r')

str = file.read()
print(f'str: {str}')

file.close()

str.replace('Python' , '파이썬', 2)

  • 내가 읽은 파일 중에 Python 이라고 되어있는 것 2개를 파이썬 으로 바꾸겠다.
file = open('파이썬 파일 주소', 'r')
str = file.read()
print(f'str: {str}')
str = str.replace('Python', '파이썬', 2)
print(f'str: {str}') 
file.close()
  • 파일을 다양한 방식으로 open 할 수 있다.
  • 쓰기 모드: w, a, x
  • 읽기 모드: r
uri = '/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt'

# 'w' 모드
file = open(uri + 'hello.txt', 'w')
file.write('hello python')
file.close()

# 'a' 모드
file = open(uri + 'hello.txt', 'a')
file.write('\nnice to meet you')
file.close()

# 'x' 모드
# file = open(uri + 'hello.txt', 'x')
# file.write('\nnice to meet you')
# file.close()

# 'r' 모드
file = open(uri + 'hello.txt', 'r')
str = file.read()
print(f'str: {str}')
file.close()
예제 1) 사용자가 입력한 숫자에 대한 소수를 구하고 이를 파일에 작성해보자. 
uri = '/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt'

def writePrimeNumber(n):
    file = open('uri' + 'prime_numbers.txt', 'a')
    file.write(str(n))
    file.write('\n')
    file.close()

inputNumber = int(input('0보다 큰 정수 입력: '))
for number in range(2,(inputNumber +1)):
    flag = True
    for n in range(2, number):
        if number % n ==0:
            flag = False
            break

    if flag:
        writePrimeNumber(number)
  • with ~ as : 파일 닫기(close) 생략 가능
1) 기본적인 파일 쓰기, 읽기

file = open(uri + '5_037.txt', 'a')
file.write('python study')
file.close()

file = open(uri + '5_037.txt', 'r')
print(file.read())
file.close()

2) with ~ as 를 이용한 파일 닫기가 생략된 과정

with open(uri + '5_037.txt', 'a') as f:
    f.write('python study!!')

with open(uri + '5_037.txt', 'r') as f:
    print(f.read())
# 실습: 로또 번호 용지 만들기
import random

uri = '/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt'

def writeNumbers(nums):
    for idx, num in enumerate(nums):
        with open(uri + 'lotto.txt', 'a') as f:
            if idx < len(nums) - 2:
                f.write(str(num) + ',')
            elif idx == len(nums) - 2:
                f.write(str(num))
            elif idx == len(nums) - 1:
                f.write('\n')
                f.write('Bonus: ' + str(num))
                f.write('\n')

rNums = random.sample(range(1,46), 7)
print(f'rNums: {rNums}')

writeNumbers(rNums)
  • writeliens(): 리스트(List) 또는 튜플 데이터를 파일에 쓰기 위한 함수.
languages = ['c/c++', 'java', 'c#', 'python', 'javascript']

uri = '/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt'

for item in languages:
    with open(uri + 'languages.txt', 'a') as f:
        f.write(item)
        f.write('\n')
        

# writelines()를 이용하면 훨씬 쉽게 리스트 반복 가능

with open(uri + 'languages.txt', 'a') as f:
    f. writelines(languages)
    

# 개행을 하려면

with open(uri + 'languages.txt', 'a') as f:
    f.writelines(item + '\n' for item in languages)

with open(uri + 'languages.txt', 'r') as f:
    print(f.read())
# 실습: 딕셔너리에 저장된 과목별 점수를 파일에 저장하는 코드 작성

uri = '/Users/chulmin/Library/Mobile Documents/com~apple~CloudDocs/pythonTxt'

scoreDic = {'kor': 85, 'eng': 90, 'mat': 92, 'sci': 79, 'his': 82}

for key in scoreDic.keys():
    with open(uri + 'scoreDic.txt', 'a') as f:
        f.write(key + '\t:' + str(scoreDic[key]) + '\n')

# scoreDic 모양 그대로 텍스트 파일에 입력
with open(uri + 'scores.txt', 'a') as f:
    print(scoreDic, file=f)
  • readlines(): 파일의 모든 데이터를 읽어서 리스트 형태로 반환한다.
with open(uri + 'lans.txt', 'r') as f:
    lanList = f.readlines()

print(f'lanList: {lanList}')
print(f'lanList type: {type(lanList)}')
  • readline(): 한 행을 읽어서 문자열로 반환한다.
with open(uri + 'lans.txt', 'r') as f:
    line = f.readline()

    while line != '':
        print(f'line: {line}', end='')
        line = f.readline()
# 실습(list, split, strip, dictionary 개념 필요)

scoresDic = {}

with open(uri + 'scores.txt', 'r') as f:
    line = f.readline()

    while line != '':
        tempList= line.split(':')
        scoresDic[tempList[0]] = int(tempList[1].strip('\n'))
        line = f.readline()

print(f'scoresDic: {scoresDic}')

[오늘의 소감]

파이썬 중급 문제풀이를 조금이나마 수월하게 하기 위해, 기초수학 파트를 먼저 공부하고 돌아왔는데, 돌아오니 파이썬 중급 개념을 다 까먹었다 ㅋㅋㅋㅋㅋ

반복, 또 반복만이 유일한 방법이지 않을까 싶다..

profile
늘 온 마음을 다해 :)

0개의 댓글