Pythonは2026年現在も世界で最も人気のあるプログラミング言語の一つです。AIブームの追い風も受け、データサイエンス・機械学習・Web開発・自動化など幅広い分野で活用されています。
Pythonのインストールと環境構築(2026年版)
# pyenvでPythonのバージョン管理(推奨)
brew install pyenv # macOS
echo 'eval "$(pyenv init -)"' >> ~/.zshrc
source ~/.zshrc
pyenv install 3.12.0
pyenv global 3.12.0
# 仮想環境の作成
python -m venv myenv
source myenv/bin/activate # macOS/Linux
# 主要パッケージのインストール
pip install requests pandas numpy scikit-learn fastapi uvicorn
Pythonの基本文法:型ヒント付き実践コード
from typing import Optional
from dataclasses import dataclass
# 変数と型ヒント
name: str = "Tech Athletes"
age: int = 25
is_active: bool = True
# リスト内包表記
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
# dataclassによるデータモデル
@dataclass
class Engineer:
name: str
age: int
skills: list[str]
salary: Optional[float] = None
def introduce(self) -> str:
return f"私は{self.name}、{', '.join(self.skills)}が得意です。"
engineer = Engineer("kasata", 30, ["Python", "AWS", "TypeScript"])
print(engineer.introduce())
Python非同期処理(asyncio + aiohttp)
import asyncio
import aiohttp
async def fetch_url(session: aiohttp.ClientSession, url: str) -> str:
async with session.get(url) as response:
return await response.text()
async def fetch_multiple(urls: list[str]) -> list[str]:
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
return await asyncio.gather(*tasks)
asyncio.run(fetch_multiple(["https://api.github.com/users/torvalds"]))
Pandasでデータ分析
import pandas as pd
import numpy as np
# DataFrameの基本操作
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie"],
"salary": [400000, 600000, 800000],
"department": ["Engineering", "Marketing", "Engineering"]
})
# 集計・フィルタリング
print(df.groupby("department")["salary"].mean())
engineers = df[df["department"] == "Engineering"]
df["monthly_salary"] = df["salary"] / 12
scikit-learnで機械学習入門
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_iris
# データ準備
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=42
)
# モデル学習・評価
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
accuracy = accuracy_score(y_test, model.predict(X_test))
print(f"正解率: {accuracy:.4f}")
FastAPIでWeb API開発
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI(title="Tech Athletes API")
class User(BaseModel):
name: str
email: str
age: int
users = []
@app.get("/users")
async def get_users():
return users
@app.post("/users", status_code=201)
async def create_user(user: User):
users.append(user)
return user
# uvicorn main:app --reload で起動
Python学習ロードマップ
- 入門(1〜2ヶ月):基本文法・リスト・辞書・関数・クラス・型ヒント
- 中級(3〜6ヶ月):非同期処理・デコレーター・テスト(pytest)
- データサイエンス特化:Pandas・NumPy・Matplotlib・scikit-learn
- Web開発特化:FastAPI・Django・SQLAlchemy・Docker
- AI/ML特化:PyTorch・TensorFlow・LangChain・Hugging Face
Pythonをマスターすることで、AIエンジニア・データサイエンティスト・バックエンドエンジニアとして高い市場価値を持てます。年収800万円〜1,500万円のAIエンジニア職への第一歩として、ぜひ習得しましょう。