230906_스터디노트

Sihyun Kim·2023년 9월 6일

🙄 자꾸 헷갈려서 혼자 보려고 써놓는 노트

  • 클래스는 어벤져스의 비젼 같은 존재 (뭔가 능력이 엄청 많고, 혼자 오롯이 존재함)
    class Vision:
  • 특수 고글을 이용하면 비젼의 능력을 가져다 쓸 수 있다
    (수정해서 쓸 순 있는데, 비젼이 가지고 있는 성격 자체를 바꾸진 않음)
  • 스파이더맨(객체)한테 특수 고글을 씌워주자
    spiderman = Vision()
  • 이제 스파이더맨은 비젼이 가지고 있는 능력을 가져다 쓸 수 있음
    spiderman.num1 = 10
    spiderman.num2 = 20
    print(spiderman.add())
  • 비젼이 가지고 있던 num1, num2 라는 미지의 존재를 스파이더맨이 정의하고,
    그 정의를 활용해서 add라는 능력을 활용하였다

사용자 Exception 클래스

class NotUseZeroException(Exception):

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

def divCal(num1, num2):

     if num2 == 0:
         raise NotUseZeroException(num2)

     else:
         print(f'{num1}/{num2}= {num1 / num2}')


userNum1 = int(input('숫자1 입력: '))
userNum2 = int(input('숫자2 입력: '))

try:
    divCal(userNum1, userNum2)
except NotUseZeroException as e:
    print(e)

사용자 Exception 클래스 (실습)

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 = 'admin1234'
userPW = input('input admin password: ')

try:
    if len(userPW) < 5:
        raise PasswordLengthShortException(userPW)

    elif len(userPW) > 10:
        raise PasswordLengthLongException(userPW)

    elif userPW != adminPW:
        raise PasswordWrongException(userPW)

    elif userPW == adminPW:
        print('빙고!')

except PasswordLengthShortException as e1:
    print(e1)

except PasswordLengthLongException as e2:
    print(e2)

except PasswordWrongException as e3:
    print(e3)
  • 실습 전 예제처럼 def userPWcheck를 만들었다가, 실패 😅
  • 연산 필요없이 길이 체크만 하면 되니까 try +if ... except 로 만들면 되는 거였음
  • except가 저렇게 여러줄 나올 수도 있었구나
  • while문을 넣어서 userPW가 틀리면 3번의 시도 후에 종료되는 걸 해보고 싶은데 자꾸 무한루프에 걸렸..지만 코드 열심히 들여다보면서 생각하니 해결!
    (문제점: userPW input을 while문 밖에서 받게 되어서, 틀린 비번 이후에 다시 input을 못 받는거였다)
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 = 'admin1234'
flag = True
trial = 0

while flag and trial < 3:

    userPW = input('input admin password: ')

    try:
        if len(userPW) < 5:
            raise PasswordLengthShortException(userPW)

        elif len(userPW) > 10:
            raise PasswordLengthLongException(userPW)

        elif userPW != adminPW:
            raise PasswordWrongException(userPW)

        elif userPW == adminPW:
            print('빙고!')
            flag = False

    except PasswordLengthShortException as e1:
        print(e1)

    except PasswordLengthLongException as e2:
        print(e2)

    except PasswordWrongException as e3:
        print(e3)

    trial += 1

    if flag == True and trial == 3:
        print('입력 시도 횟수 초과')

텍스트 파일 쓰기

open(), read(), write(), close()

'w'모드: 쓰기 모드

  • 파일이 없으면 새로 생성함
  • 기존에 있던 텍스트를 전부 지워버리고 새로운 텍스트로 대체함
file1 = open('C:/pythontxt/test.txt', 'w')

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

file1.close()

⏰ 현재 시각 정보 가져오기

import time
lt = time.localtime()
year = lt.tm_year 
month = lt.tm_mon 
day = lt.tm_mday
dateStr = time.strftime('%Y-%m-%d %I:%M:%S %p') #12시 기준 + ampm 표시
dateStr2 = time.strftime('%Y-%m-%d %H:%M:%S')	#24시 기준
import time

lt = time.localtime()

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

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

file2 = open('C:/pythontxt/test.txt', 'w')
file2.write(dateStr + todaySchedule)
file2.close()

텍스트 파일 읽기

file3 = open('C:/pythontxt/test.txt', 'r')
str = file3.read()
print(str)
file3.close()
file = open('C:/pythontxt/aboutPython.txt','r')
str = file.read()
print(str)

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

file.close()

file = open('C:/pythontxt/aboutPython.txt','w')
file.write(str2)
file.close()

텍스트 파일 열기

  • 'w': 쓰기 전용 (파일이 있으면 덮어씌움, 없으면 만듦)
  • 'a': 쓰기 전용 (파일이 있으면 덧붙임)
  • 'x': 쓰기 전용 (파일이 있으면 에러 발생)
  • 'r': 읽기 전용 (파일이 없으면 에러 발생)
uri = 'C:/pythontxt/'

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

# 'a' 파일 모드
file2 = open(uri+'hello.txt', 'a')
file2.write('\nNice to meet you')
file2.close()											#위에서 만든 파일의 내용에 추가

# 'x' 파일 모드
file3 = open(uri+'hello2.txt','x')
file3.write('Hey')
file3.close()											#새로운 파일 생성

# 'r' 파일 모드
file4 = open (uri + 'hello2.txt', 'r')
str = file4.read()
print(str)
file4.close()											#Hey 출력

텍스트 파일 열기 (실습)

uri = 'C:/pythontxt/'

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

userNum = int(input('숫자 입력: '))

for number in range (2, userNum+1):
    flag = True

    for i in range (2, number):
        if number % i == 0:
           flag = False
           break

    if flag:
        writePrimeNumber(number)
  • write 할 때, 숫자는 str으로 캐스팅을 해야 오류가 안남
  • 개행 할 땐 '\n'
  • 소수는 나올 때마다 긴장타서 이제 통째로 외워버려야겠음 ✨
profile
문과이과예체능통합형인재

0개의 댓글