#1) 데이터 타입 + 내장함수
def show_basic_types() -> None:
a = 10 # int
b = 3.14 # float (double이라는 말도 흔히 쓰지만, 파이썬은 float)
c = "hello" # str
d = True # bool
e = [1, 2, 3] # list
f = {"x": 1, "y": 2} # dict
print("== Basic Types ==") for name, value in [("a", a), ("b", b), ("c", c), ("d", d), ("e", e), ("f", f)]: print(f"{name} = {value}, type = {type(value)}")
# 내장함수 예시 print("\n== Built-in Functions ==") print("len(c) =", len(c)) print("len(e) =", len(e)) print("sum(e) =", sum(e)) print("sorted(e, reverse=True) =", sorted(e, reverse=True)) print("max(e) =", max(e), "min(e) =", min(e))
def save_lines(filepath: str, lines: list[str]) -> None:
# 파일 출력(쓰기) with open(filepath, "w", encoding="utf-8") as f: for line in lines: f.write(line + "\n")
def load_lines(filepath: str) -> list[str]:
# 파일 입력(읽기) with open(filepath, "r", encoding="utf-8") as f: return [line.rstrip("\n") for line in f]
def add(x: int, y: int) -> int:
"""함수는 입력을 받아 처리하고 결과를 반환한다."""
return x + y
def describe_value(value) -> str:
"""
파이썬은 타입을 코드에 강제하지 않아도 되고(동적 타이핑),
필요하면 type() 같은 내장함수로 확인 가능.
"""
return f"value={value}, type={type(value).name}"
내장함수: 파이썬 내에서 내장되어있는 함수 ex) print, type , len
외장함수 : 내가 필요에 따라 만드는 함수
class Student:
"""
클래스 = 설계도(데이터 + 기능(메서드))
객체/인스턴스 = 클래스로부터 실제로 만들어진 실체
"""
def __init__(self, name: str, scores: list[int]):
self.name = name # 속성(데이터)
self.scores = scores # 속성(데이터)
# 메서드(클래스 안의 함수)
def average(self) -> float:
return sum(self.scores) / len(self.scores) if self.scores else 0.0
def add_score(self, score: int) -> None:
self.scores.append(score)
def summary(self) -> str:
return f"{self.name}: scores={self.scores}, avg={self.average():.2f}"
~~
def main() -> None:
# (1) 데이터 타입 + 내장함수
show_basic_types()
# (2) 함수(def)
print("\n== Functions ==")
result = add(7, 5)
print("add(7, 5) =", result)
print(describe_value(result))
print(describe_value("AI & Robotics"))
# (3) 파일 I/O
print("\n== File I/O ==")
path = "study_notes.txt"
notes = [
"Today I studied: data types, built-in functions, functions, file I/O, classes/objects/instances.",
"Python is dynamically typed, but type hints are optional.",
f"Example result: add(7, 5) = {result}",
]
save_lines(path, notes)
loaded = load_lines(path)
print(f"Saved to {path}, then loaded back:")
for line in loaded:
print(" -", line)
# (4) 클래스/객체/인스턴스
print("\n== Class / Object / Instance ==")
s1 = Student("Kunhee", [90, 85, 100]) # s1: 객체(=인스턴스)
print("type(s1) =", type(s1))
print("s1.summary() ->", s1.summary())
s1.add_score(95)
print("after add_score(95) ->", s1.summary())
if __name__ == "__main__":
main()
~~
if name == "main": main() 는 “이 파일을 직접 실행했을 때만 main()을 호출해라”
네, 정확히 그 뜻이야. 👍
import a는 다른 파일(예:b.py)에서a.py를 불러오는 것을 말해.
아주 명확하게 구조로 설명해줄게.
project/
├─ a.py
└─ b.py
# a.py
def main():
print("a.py main 실행")
def hello():
print("Hello from a.py")
print("a.py loaded")
if __name__ == "__main__":
main()
# b.py
import a
print("b.py 실행 중")
a.hello()
python a.py__name__ == "__main__" → True출력:
a.py loaded
a.py main 실행
python b.py출력:
a.py loaded
b.py 실행 중
Hello from a.py
👉 여기서 핵심:
import a 할 때 a.py 전체가 한 번 로드됨
하지만
if __name__ == "__main__":
main()
이 부분은 실행되지 않음
이 구조 덕분에:
a.py를
👉 그래서 실무, 연구, 대회 코드 전부 이 패턴을 사용함.
✅
import a란
“다른 파일(b.py)에서 a.py를 불러와서 안에 있는 함수·클래스·변수를 사용하는 것”