Python
エンジニアのためのWebチートシート
Pythonは、シンプルで読みやすい構文が特徴の汎用プログラミング言語です。 データ型、制御構文、関数、クラス、リスト操作、ファイル操作などの基本をチートシートにまとめました。
基本構文
変数
Pythonは動的型付け言語で、型宣言は不要です。
# 変数代入 name = "Python" age = 30 is_active = True pi = 3.14 # 複数代入 x, y, z = 1, 2, 3 a = b = c = 0 # 型ヒント(Python 3.6+) name: str = "Python" age: int = 30 items: list[str] = ["a", "b"]
型変換
型を変換する組み込み関数です。
int("42") # 42 float("3.14") # 3.14 str(42) # "42" bool(1) # True bool(0) # False bool("") # False list((1, 2)) # [1, 2] tuple([1, 2]) # (1, 2) set([1, 1, 2]) # {1, 2} type(42) # <class 'int'>
データ型
文字列
文字列の基本操作です。
s = "Hello, World!" s = 'Hello' s = """Multi line""" # f-string (Python 3.6+) name = "World" f"Hello, {name}!" f"{2 + 3 = }" # "2 + 3 = 5" f"{name!r}" # "'World'" f"{3.14159:.2f}" # "3.14" # スライス s[0] # 'H' s[-1] # '!' s[0:5] # 'Hello' s[::-1] # 逆順
文字列メソッド
よく使う文字列メソッドです。
s.upper() # "HELLO" s.lower() # "hello" s.strip() # 前後の空白除去 s.split(",") # ["a", "b"] ",".join(["a", "b"]) # "a,b" s.replace("old", "new") s.startswith("He") # True s.endswith("!") # True s.find("lo") # 3 (見つからないと-1) s.count("l") # 2 s.isdigit() # False len(s) # 13
数値
数値型と基本演算です。
# 四則演算 10 + 3 # 13 10 - 3 # 7 10 * 3 # 30 10 / 3 # 3.3333... 10 // 3 # 3 (切り捨て) 10 % 3 # 1 (余り) 10 ** 3 # 1000 (べき乗) # 組み込み関数 abs(-5) # 5 round(3.7) # 4 max(1, 2, 3) # 3 min(1, 2, 3) # 1 sum([1,2,3]) # 6
制御フロー
if / elif / else
条件分岐です。インデントでブロックを表します。
if x > 0: print("positive") elif x == 0: print("zero") else: print("negative") # 三項演算子 result = "even" if x % 2 == 0 else "odd" # match文 (Python 3.10+) match status: case 200: print("OK") case 404: print("Not Found") case _: print("Other")
for ループ
イテラブルオブジェクトを反復処理します。
for i in range(5): # 0,1,2,3,4 print(i) for i in range(1, 10, 2): # 1,3,5,7,9 print(i) for item in ["a", "b", "c"]: print(item) for i, item in enumerate(["a", "b"]): print(i, item) # 0 a, 1 b for k, v in dict.items(): print(k, v) # break / continue for i in range(10): if i == 5: break if i % 2 == 0: continue
内包表記
リスト・辞書・集合を簡潔に生成します。
# リスト内包表記 squares = [x**2 for x in range(10)] evens = [x for x in range(10) if x % 2 == 0] # 辞書内包表記 d = {k: v for k, v in pairs} # 集合内包表記 s = {x**2 for x in range(10)} # ジェネレータ式 gen = (x**2 for x in range(10))
関数
関数定義
def キーワードで関数を定義します。
def greet(name: str) -> str: return f"Hello, {name}!" # デフォルト引数 def greet(name: str = "World") -> str: return f"Hello, {name}!" # 複数の戻り値 def min_max(items): return min(items), max(items) lo, hi = min_max([3, 1, 4, 1, 5])
ラムダ式
無名関数を簡潔に定義します。
square = lambda x: x ** 2 add = lambda x, y: x + y # sorted + lambda users = [{"name": "B"}, {"name": "A"}] sorted(users, key=lambda u: u["name"]) # map / filter list(map(lambda x: x*2, [1,2,3])) # [2,4,6] list(filter(lambda x: x>2, [1,2,3])) # [3]
*args / **kwargs
可変長引数を受け取ります。
# *args: 可変長位置引数(タプル) def sum_all(*args): return sum(args) sum_all(1, 2, 3) # 6 # **kwargs: 可変長キーワード引数(辞書) def info(**kwargs): for k, v in kwargs.items(): print(f"{k}: {v}") info(name="Taro", age=25)
デコレータ
関数やクラスの機能を拡張します。
import functools def timer(func): @functools.wraps(func) def wrapper(*args, **kwargs): import time start = time.time() result = func(*args, **kwargs) print(f"{func.__name__}: {time.time()-start:.2f}s") return result return wrapper @timer def slow_function(): import time time.sleep(1)
データ構造
リスト操作
リストの主な操作メソッドです。
lst = [1, 2, 3] lst.append(4) # [1,2,3,4] lst.insert(0, 0) # [0,1,2,3,4] lst.extend([5, 6]) # [0,1,2,3,4,5,6] lst.pop() # 6, lst=[0,1,2,3,4,5] lst.pop(0) # 0, lst=[1,2,3,4,5] lst.remove(3) # [1,2,4,5] lst.sort() # ソート(破壊的) sorted(lst) # ソート(非破壊的) lst.reverse() # 逆順 lst.index(2) # 1 len(lst) # 4 2 in lst # True
辞書操作
辞書の主な操作メソッドです。
d = {"name": "Taro", "age": 25} d["email"] = "taro@example.com" # 追加 d["name"] # "Taro" d.get("name") # "Taro" d.get("phone", "N/A") # "N/A" d.keys() # dict_keys d.values() # dict_values d.items() # dict_items d.pop("age") # 25 d.update({"city": "Tokyo"}) del d["city"] "name" in d # True len(d) # 2
セット & タプル
集合型とイミュータブルなタプルです。
# タプル(イミュータブル) t = (1, 2, 3) t[0] # 1 x, y, z = t # アンパック # セット(集合) s = {1, 2, 3} s.add(4) s.remove(1) s.discard(99) # エラーなし # 集合演算 a = {1, 2, 3} b = {2, 3, 4} a | b # {1,2,3,4} 和集合 a & b # {2,3} 積集合 a - b # {1} 差集合 a ^ b # {1,4} 対称差
クラス
クラス定義
classキーワードでクラスを定義します。
class User: def __init__(self, name: str, age: int): self.name = name self.age = age def greet(self) -> str: return f"I'm {self.name}, {self.age} years old" def __str__(self) -> str: return f"User({self.name})" user = User("Taro", 25) print(user.greet())
継承
クラスを継承して機能を拡張します。
class Animal: def __init__(self, name: str): self.name = name def speak(self) -> str: raise NotImplementedError class Dog(Animal): def speak(self) -> str: return f"{self.name}: Woof!" class Cat(Animal): def speak(self) -> str: return f"{self.name}: Meow!" dog = Dog("Pochi") print(dog.speak()) # "Pochi: Woof!"
dataclass
データ保持用のクラスを簡潔に定義します。
from dataclasses import dataclass, field @dataclass class Point: x: float y: float z: float = 0.0 @dataclass(frozen=True) # イミュータブル class Config: host: str port: int = 8080 tags: list = field(default_factory=list) p = Point(1.0, 2.0) print(p) # Point(x=1.0, y=2.0, z=0.0)
ファイル & 例外処理
ファイル読み書き
with文を使ったファイルの読み書きです。
# 読み込み with open("file.txt", "r", encoding="utf-8") as f: content = f.read() # 全体 lines = f.readlines() # 行リスト # 書き込み with open("file.txt", "w", encoding="utf-8") as f: f.write("Hello\n") # 追記 with open("file.txt", "a") as f: f.write("World\n") # JSON import json with open("data.json") as f: data = json.load(f) with open("out.json", "w") as f: json.dump(data, f, indent=2)
例外処理
try/except で例外を処理します。
try: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}") except (TypeError, ValueError): print("Type or Value error") except Exception as e: print(f"Unexpected: {e}") else: print("No error") finally: print("Always executed") # カスタム例外 class MyError(Exception): pass raise MyError("Something wrong")
モジュール & 環境
import
モジュールのインポート方法です。
import os import json from pathlib import Path from datetime import datetime, timedelta from collections import defaultdict, Counter from typing import Optional, Union # エイリアス import numpy as np import pandas as pd # 相対インポート from . import module from ..utils import helper
仮想環境
プロジェクトごとに独立したPython環境を作ります。
# venv python -m venv .venv source .venv/bin/activate # Mac/Linux .venv\Scripts\activate # Windows deactivate # pip pip install requests pip install -r requirements.txt pip freeze > requirements.txt # uv (高速パッケージマネージャ) uv venv uv pip install requests