본문 바로가기

부스트캠프 AI Tech/Python

(10)
[10] configparser, argparser configparser - 파일에 parser 프로그램의 실행 설정을 file에 저장함 Section, Key, Value 값의 형태로 설정된 설정 파일을 사용 설정파일을 Dict Type으로 호출후 사용 'example.cfg' [SectionOne] Status: Single Name: Derek Value: Yes Age: 30 Single: True [SectionTwo] FavoriteColor = Green [SectionThree] FamilyName: Johnson import configparser config = configparser.ConfigParser() config.read('example.cfg') config.sections() # sections 확인 for key in ..
[09] File Handling file_handling¶ 파이썬은 파일 처리를 위해 "open" 키워드를 사용한다. f = open("", "") f.close() r 읽기모드 - 파일을 읽기만 할 때 w 쓰기모드 - 파일에 내용을 쓸 때 a 추가모드 - 파일의 마지막에 새로운 내용을 추가 할 때 read() - txt파일 안에 있는 내용을 문자열로 반환¶ f = open("i_have_a_dream.txt", "r" ) contents = f.read() print(contents) f.close() with 구문과 함께 사용하기¶ with open("i_have_a_dream.txt", "r") as my_file: contents = my_file.read() print (type(contents), contents) 여러가지 ..
[08] Exception 예외처리¶ try: 예외 발생 가능 코드 except : 예외 발생시 대응하는 코드 try: 예외 발생 가능 코드 except : 예외 발생시 동작하는 코드 else: 예외가 발생하지 않을 때 동작하는 코드 try: 예외 발생 가능 코드 except : 예외 발생시 동작하는 코드 finally: 예외 발생 여부와 상관없이 실행됨 Built-in Exception¶ Exception 이름 내용 IndexError List의 index 범위를 넘어갈 때 NameError 존재하지 않은 변수 호출 ZeroDivisionError 0으로 나눌 때 ValueError 변환할 수 없는 문자/숫자를 변환할 때 FileNotFoundError 존재하지 않은 파일을 호출할 때 강제 Exception 발생 -> raise..
[07] 내장함수 property와 Decorator class C: def __init__(self): self.__age = 12 def print_age(self): return self.__age def change_age(self, new_age): self.__age = new_age age = property(print_age, change_age) a.__age = 13 위 코드를 실행하면 __age는 private 로 되어있기 때문에 오류가 뜬다. 그래서 __age를 보거나 변경할 때 클래스 내 get, set 함수를 구현하여 변경한다. 위 코드에선 print_age와 change_age를 사용해야한다. a.change_age(3) a.print_age() 이를 한번에 property 함수를 이용해 a.age 를 사용 가능하게 할 수 있다...
[06] Class, Inheritance, Visibility 축구 선수 정보 class로 구현¶ In [1]: class SoccerPlayer(object): def __init__(self, name : str, position : str, back_number : int): self.name = name self.position = position self.back_number = back_number # 반드시 self 를 추가해야만 class 함수로 인정됨 def change_back_number(self, new_number): print(f"change number from {self.back_number} to {new_number}") self.back_number = new_number # 인스턴스 print 할때 __str__ 매서드 사용 de..
[05] 가변인자 def kwargs_test(one, two=3, *args, **kwargs): # * args 튜플형태로 # ** kwargs 사전형태로 # *(1,2,3,4,5) -> 1,2,3,4,5 unpacking 시에도 * 사용 print(one + two + sum(args)) print(two) print(args) print(kwargs) kwargs_test(10, 20, 1, 2, 3, 4, first = 3, second = 2) 40 20 (1, 2, 3, 4) {'first': 3, 'second': 2}
[04] Black으로 파이썬 코드 스타일 통일하기 https://www.daleseo.com/python-black/ Black으로 파이썬 코드 스타일 통일하기 Engineering Blog by Dale Seo www.daleseo.com
[03] 문자열 함수 정리 len(a) a.upper() a.lower() a.capitalize() a.title() a.count('abc') a.find('abc') a.startswith('abc') a.endswith('abc') a.strip() a.rstrip() a.lstrip() a.split() a.split('abc') a.isdigit() a.islower() a.isupper()
[02] if __name__=="__main__" if __name__=="__main__" __name__ 은 현재 모듈의 이름을 담고있는 내장 변수이다. 이 변수는 직접 실행된 모듈의 경우 __main__이라는 값을 가지게 되며, 직접 실행되지 않은 import된 모듈은 모듈의 이름(파일명)을 가지게 된다. #module.py def hello(): print("Hello!") print(__name__) #main.py import module print(__name__) module.hello() module __main__ Hello! import module 로 module을 직접 실행 안했기 때문에 moudule의 __name__ 내장변수에는 모듈 이름(파일명) module을 가지게 되므로 module 출력. 이때 모듈에 if __name_..
[01] f - string In [1]: name = "TaeHo" age = 27 In [2]: print(f"Hello, {name}. You are {age}.") print(f'{name:20}') print(f'{name:>20}') print(f'{name:*20}') print(f'{name:*^20}') number = 3.141592653589793 print(f'{number:.2f}') In [1]: In [2]: print(f"Hello, {name}. You are {age}.") print(f'{name:20}') print(f'{name:>20}') print(f'{name:*20}') print(f'{name:*^20}') number = 3.141592653589793 print(f'{number:...