Python
Python Language
A readable general-purpose programming language. Widely used in data science, AI, and web development. Dynamic typing.
Python Language
A readable general-purpose programming language. Widely used in data science, AI, and web development. Dynamic typing.
Python is a high-level, general-purpose programming language developed in 1991 by the Dutch programmer Guido van Rossum. Its name comes from the British comedy group 'Monty Python'. It is an interpreted language that supports dynamic typing, and Python 1.0 was released in 1994, Python 2.0 in 2000, and Python 3.0 in 2008. Python 2 officially reached end of life in 2020, so Python 3.x is now the standard.
Python's design philosophy is embodied in "The Zen of Python" (PEP 20). Its core principles include "Beautiful is better than ugly" (readable code is beautiful), "Explicit is better than implicit", and "Simple is better than complex". Thanks to its syntax that uses indentation to delimit code blocks, it is highly readable and easy to learn, so it is widely used as an introductory programming language.
Its range of applications is very broad. In AI/ML, major libraries such as TensorFlow, PyTorch, and scikit-learn support Python, making it effectively the standard language. For web development there are frameworks such as Django, Flask, and FastAPI, and for data analysis there are Pandas, NumPy, and Matplotlib. It is also used extensively in automation, scripting, DevOps, and scientific research.
The core of the Python ecosystem is pip (the package manager) and PyPI (the Python Package Index). As of 2025, more than 500,000 packages are registered on PyPI. Virtual environments (venv, conda) are used to manage dependencies per project, and modern tools such as Poetry and PDM are also widely used. Python continues to evolve, with pattern matching (match-case) introduced in 3.10 and performance improvements in 3.12.
# Python 기본 문법 예제
# 1. 변수와 데이터 타입
name = "Python" # 문자열
version = 3.12 # 실수
is_awesome = True # 불리언
features = ["simple", "readable", "powerful"] # 리스트
# 2. 조건문
if version >= 3.10:
print("패턴 매칭 사용 가능!")
elif version >= 3.0:
print("Python 3 기능 사용 가능")
else:
print("업그레이드가 필요합니다")
# 3. 반복문
for feature in features:
print(f"Python is {feature}")
# 4. 함수 정의 (타입 힌팅 포함)
def greet(name: str, times: int = 1) -> str:
"""인사말을 반환하는 함수"""
return f"Hello, {name}! " * times
# 5. 클래스 정의
class Developer:
def __init__(self, name: str, language: str = "Python"):
self.name = name
self.language = language
def introduce(self) -> str:
return f"저는 {self.name}이고, {self.language}를 사용합니다."
# 6. 예외 처리
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"오류 발생: {e}")
finally:
print("정리 작업 완료")
# 리스트 컴프리헨션 - Python의 핵심 문법
# 1. 기본 리스트 컴프리헨션
squares = [x**2 for x in range(10)]
# 결과: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 2. 조건부 필터링
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# 결과: [0, 4, 16, 36, 64]
# 3. 중첩 리스트 컴프리헨션
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
# 결과: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 4. 딕셔너리 컴프리헨션
word = "python"
char_index = {char: idx for idx, char in enumerate(word)}
# 결과: {'p': 0, 'y': 1, 't': 2, 'h': 3, 'o': 4, 'n': 5}
# 5. 셋 컴프리헨션
unique_lengths = {len(word) for word in ["apple", "banana", "cherry", "date"]}
# 결과: {4, 5, 6}
# 6. 제너레이터 표현식 (메모리 효율적)
sum_of_squares = sum(x**2 for x in range(1000000))
# 리스트를 생성하지 않고 한 번에 하나씩 처리
# 7. 실전 예제: 파일에서 특정 라인 필터링
# config_lines = [line.strip() for line in open('config.txt')
# if line.strip() and not line.startswith('#')]
# 8. 조건부 값 변환
numbers = [1, -2, 3, -4, 5]
absolute = [x if x > 0 else -x for x in numbers]
# 결과: [1, 2, 3, 4, 5]
# 데코레이터 - Python의 강력한 메타프로그래밍 기능
import functools
import time
from typing import Callable, Any
# 1. 기본 데코레이터 - 실행 시간 측정
def timer(func: Callable) -> Callable:
"""함수 실행 시간을 측정하는 데코레이터"""
@functools.wraps(func)
def wrapper(*args, **kwargs) -> Any:
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"{func.__name__} 실행 시간: {end - start:.4f}초")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "완료"
# 2. 인자를 받는 데코레이터
def retry(max_attempts: int = 3, delay: float = 1.0):
"""재시도 데코레이터"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs) -> Any:
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_attempts - 1:
raise
print(f"시도 {attempt + 1} 실패, {delay}초 후 재시도...")
time.sleep(delay)
return wrapper
return decorator
@retry(max_attempts=3, delay=0.5)
def unstable_api_call():
import random
if random.random() < 0.7:
raise ConnectionError("API 연결 실패")
return "성공!"
# 3. 클래스 기반 데코레이터
class Cache:
"""결과를 캐싱하는 데코레이터"""
def __init__(self, func: Callable):
self.func = func
self.cache = {}
functools.update_wrapper(self, func)
def __call__(self, *args) -> Any:
if args not in self.cache:
self.cache[args] = self.func(*args)
return self.cache[args]
@Cache
def fibonacci(n: int) -> int:
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
# 4. 내장 데코레이터 활용
class MyClass:
_instance = None
@staticmethod
def utility_function():
"""인스턴스 없이 호출 가능"""
return "유틸리티 결과"
@classmethod
def get_instance(cls):
"""싱글톤 패턴 구현"""
if cls._instance is None:
cls._instance = cls()
return cls._instance
@property
def computed_value(self):
"""속성처럼 접근 가능한 메서드"""
return self._value * 2
"For this AI service backend, we'll go with Python. Our ML pipeline is based on PyTorch, and we can build the API server quickly with FastAPI. For parts that need Java's performance, we can split them off into microservices. When collaborating with the data science team, Python is the common language, so it also reduces communication costs."
"GIL stands for Global Interpreter Lock, a mutex in CPython that allows only one thread to execute Python bytecode at a time. It makes it hard to benefit from multithreading in CPU-bound tasks. As alternatives, you can separate processes with the multiprocessing module, or use asyncio for I/O-bound tasks. Recently, PEP 703 free-threaded Python was introduced experimentally in 3.13, and the removal of the GIL is in progress."
"Please add type hints to this function, in the form def process_data(data: list[dict[str, Any]]) -> pd.DataFrame. Static analysis with mypy can catch bugs in advance, and IDE autocompletion also works well. Since 3.10, built-in types can be used directly, as in list[dict], so you can also reduce imports of the typing module."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
There is no performance benefit in CPU-bound multithreading. If you need parallel processing, use multiprocessing, concurrent.futures, or tools such as Cython/Numba. For I/O-bound tasks, asyncio or threading is effective.
Python 2 reached end of support in January 2020. When migrating legacy code, pay attention to the print function, integer division (//, /), string encoding (unicode default), and library changes (such as ConfigParser). The 2to3 tool and the python-future library can help with migration.
Dynamic typing is convenient, but it can cause bugs in large-scale projects. Use type hints (PEP 484) and static analysis tools such as mypy and Pyright. Adding runtime type validation with libraries such as Pydantic and attrs makes your code even safer.
Always use a virtual environment for each project (venv, conda, poetry). Pin versions with == in requirements.txt, and manage dependency lock files with pip-tools or Poetry. Global installs cause version conflicts.