본문 바로가기

Python 기초

(18)
18. 표준 입출력 👉 왼쪽정렬 : ljust, 오른쪽정렬 : rjust scores = {"수학": 0, "영어": 50, "코딩": 100} for subject, score in scores.items(): print(subject.ljust(4), str(score).rjust(4), sep=":") # 1. # 변수를 딕셔너리로 한 후, # .items() 로 하면 앞 쪽 for문 뒤 각각의 변수가 key, vlaue 이다. # 2. # 왼쪽정렬 = ljust(n) -> n만큼 칸을 갖고 왼쪽정렬 # 오른쪽정렬도 마찬가지 👉 빈칸 0으로 채우기 : zfill # 은행 대기순번표 # 001, 002, 003, ... for num in range(1, 21): print("대기번호 :" + str(num).zfill..
17. 기본값, 가변인자 👉 기본값 def profile(name, age=29, main_lang="python"): print(f"이름: {name}, 나이:{age}, 주 사용 언어: {main_lang}") profile("헐크") profile("아이언맨") # age=29 와 같이 인자 안에 값을 정해준다 👉 가변인자 def profile(name, age, *language): print(f"이름:{name} 나이: {age}") for lang in language: print(lang, end=" ") # end=" " 를 쓰면 출력이 될 떄 줄바꾸기가 되지 않음 profile("유재석", 20, "python", "javascript") profile("정준하", 25, "python", "java", "jav..
16. 한 줄 for 문 students = [1, 2, 3, 4, 5] print(students) students = [i + 100 for i in students] print(students)
15. 리스트, 튜플, 딕셔너리 [] # 리스트 () # 튜플 {} # 딕셔너리 javascript 로 따지면, 리스트 = let 튜플 = const 딕셔너리 = 객체 정도..? ! 튜플은 내용을 변경할 수 없지만 리스트보다 속도가 빠르다.
14. continue, break 👉 continue, break absent = [2, 5] no_book = [7] for student in range(1, 11): if student in absent: continue elif student in no_book: print(f"오늘 수업은 여기까지. {student}는 교무실로 따라와") break print(f"{student}, 책을 읽어봐.") break : 조건에 맞는 문장이 나오면 프로그램 작동을 멈춘다. continue: 프로그램이 끝나는 조건이 나올 때까지 계속 수행한다.
13. 자료구조의 변경 👉 자료구조의 변경 menu = {"커피", "우유", "주스"} print(menu, type(menu)) menu = list(menu) print(menu, type(menu)) menu = tuple(menu) print(menu, type(menu)) menu = set(menu) print(menu, type(menu))
12. 클래스(Class) - 2 instance vs. static instance vs. static 인스턴스 필드 (instance field) : 객체 별로 "따로" 보관되는 데이터 스태틱 필드 (static field) : 모든 객체가 "공유" 하는 데이터 class Point: def __init__(self, x = 0, y = 0): self.x = x; self.y = y; ex1 = Point(1,2) ex2 = Point(3,4) 인스턴스 필드 x,y 를 가진 Point 클래스 객체를 두 개 생성했다. 각 객체의 필드들은 객체의 __dict__ 어트리트뷰트에 저장된다. 스태틱 필드들은 모든 객체들의 타입을 관리하는 "타입 객체" 에 저장된다. 스태틱 필드의 문법 class Point: count = 0 def __init__(self, x = 0, y ..
11. 클래스 (Class) - 1 클래스 객체 생성 class ClassName : pass c = ClassName() " 객체 = 클래스 이름 " 클래스의 생성자와 소멸자 class One : def __init__(self) : print('constructor') def __del__(self) : print('destructor') ex1 = One() class Two : def __init__(self, a, b, c) : print(f'constructor({a},{b},{c})') def __del__(self) : print('destructor') ex2 = Two(1,2,3) 생성자(constructor) : 클래스 객체가 생성 될 때 호출된다. 생성자는 __init__ 이라는 미리 지정된 이름을 사용해야 하며 첫 ..