AI Speak and write (1)

SON·2026년 1월 16일

AI Speak and wirte (1)

data type : int, string float, dould -> 타입 힌트 주는 것 좋음

#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))

file input, output :

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(함수) : 입력을 받아서 출력을 줌

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}"

class : 메서드(함수)를 한데 묶어서 하나의 객체, 클래스는 설계도

~~
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를 불러오는 것을 말해.

아주 명확하게 구조로 설명해줄게.


1️⃣ 파일 구조 예시

project/
 ├─ a.py
 └─ b.py

2️⃣ a.py (불러올 파일)

# a.py
def main():
    print("a.py main 실행")

def hello():
    print("Hello from a.py")

print("a.py loaded")

if __name__ == "__main__":
    main()

3️⃣ b.py (실행 파일)

# b.py
import a

print("b.py 실행 중")
a.hello()

4️⃣ 실행 결과 차이

python a.py

  • a.py가 직접 실행
  • __name__ == "__main__" → True

출력:

a.py loaded
a.py main 실행

python b.py

  • b.py가 직접 실행
  • a.py는 import됨

출력:

a.py loaded
b.py 실행 중
Hello from a.py

👉 여기서 핵심:

  • import a 할 때 a.py 전체가 한 번 로드됨

  • 하지만

    if __name__ == "__main__":
        main()

    이 부분은 실행되지 않음


5️⃣ 왜 이런 구조가 중요하냐?

이 구조 덕분에:

  • a.py

    • 실행용 스크립트로도 쓰고
    • 라이브러리(모듈)로도 쓸 수 있음

👉 그래서 실무, 연구, 대회 코드 전부 이 패턴을 사용함.


6️⃣ 한 줄로 정리

import a
“다른 파일(b.py)에서 a.py를 불러와서 안에 있는 함수·클래스·변수를 사용하는 것”


profile
Like it, and it will be the best.

0개의 댓글