初心者から中級者まで使える!Pythonチートシートまとめ

python

Python(パイソン)はシンプルで読みやすい文法が特徴のプログラミング言語です。

しかし、いざ書き始めると「この文法どう書くんだっけ?」と忘れてしまうことも多いはず。

そんなときに役立つのが「チートシート(早見表)」です。

本記事では、Pythonの基本文法からよく使う関数、ライブラリまで、厳選したチートシートをカテゴリ別にわかりやすく紹介します。

スポンサーリンク

基本構文

変数とデータ型

Pythonでの基本的なデータの扱い方です。

# コメント(説明文)
# これはコメントです

# 変数の代入
x = 10                    # 数値(整数)
y = 3.14                  # 数値(小数)
name = "Alice"            # 文字列
is_student = True         # ブール値(TrueまたはFalse)

# 文字列の計算
full_name = "Alice" + " " + "Smith"    # "Alice Smith"
repeat_text = "Hello " * 3             # "Hello Hello Hello "

# 数値の計算
sum_value = 10 + 5        # 足し算: 15
diff = 10 - 3             # 引き算: 7
product = 4 * 3           # 掛け算: 12
division = 10 / 3         # 割り算: 3.333...
floor_div = 10 // 3       # 割り算(整数): 3
remainder = 10 % 3        # 余り: 1
power = 2 ** 3            # 累乗: 8


標準ライブラリと組み込み関数

数学系ライブラリ

計算や数値処理に必要な機能です。

import math

# 基本的な数学関数
print(math.sqrt(16))        # 平方根: 4.0
print(math.pow(2, 3))       # 累乗: 8.0
print(math.ceil(4.3))       # 切り上げ: 5
print(math.floor(4.7))      # 切り捨て: 4
print(math.round(4.6))      # 四捨五入: 5

# 三角関数
print(math.sin(math.pi/2))  # サイン: 1.0
print(math.cos(0))          # コサイン: 1.0
print(math.tan(math.pi/4))  # タンジェント: 1.0

# 常数と対数
print(math.exp(1))          # eの累乗: 約2.718
print(math.log(10))         # 自然対数
print(math.log10(100))      # 常用対数: 2.0

# 便利な定数
print(math.pi)              # 円周率: 3.14159...
print(math.e)               # ネイピア数: 2.71828...

ランダム数生成

乱数やランダムな選択を作成します。

import random

# 基本的な乱数操作
print(random.random())            # 0.0〜1.0の乱数
print(random.randint(1, 10))      # 1〜10の整数
print(random.uniform(1.0, 10.0))  # 1.0〜10.0の少数

# リストからランダム選択
fruits = ["りんご", "バナナ", "みかん"]
print(random.choice(fruits))      # ランダムに1つ選択

# 複数のランダム選択
print(random.sample(fruits, 2))   # 2つをランダム選択

# リストの順番をシャッフル
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)

# 乱数シードの設定(再現性のため)
random.seed(42)
print(random.randint(1, 100))     # いつも同じ結果

日付と時刻の操作

日付や時刻を扱うライブラリです。

from datetime import datetime, date, time, timedelta

# 現在の日付と時刻
now = datetime.now()
print(now)  # 例: 2025-06-13 10:00:00

# 日付の取得
today = date.today()
print(today)  # 例: 2025-06-13

# 日付のフォーマット
print(now.strftime("%Y年%m月%d日"))  # 例: 2025年06月13日
print(now.strftime("%H時%M分"))      # 例: 10時00分

# 日付の計算
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)

# 文字列を日付に変換
parsed = datetime.strptime("2025-06-01", "%Y-%m-%d")

# 曜日の取得
weekday = now.strftime("%A")  # Monday など

続いて「組み込み関数の活用」「文字列処理」のセクションを漢字かな混じり文で提供します。


組み込み関数の活用

Pythonに元から備わっている便利な関数です。

numbers = [1, 2, 3, 4, 5]

# 長さや合計、最大・最小
print(len(numbers))         # 要素数: 5
print(sum(numbers))         # 合計: 15
print(max(numbers))         # 最大値: 5
print(min(numbers))         # 最小値: 1

# 範囲生成
print(list(range(5)))           # [0, 1, 2, 3, 4]
print(list(range(1, 6)))        # [1, 2, 3, 4, 5]
print(list(range(0, 10, 2)))    # [0, 2, 4, 6, 8]

# ソート(並べ替え)
fruits = ["みかん", "りんご", "バナナ"]
print(sorted(fruits))                   # ['みかん', 'りんご', 'バナナ']
print(sorted(numbers, reverse=True))   # [5, 4, 3, 2, 1]

# 番号付きで繰り返し
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# 複数のリストを組み合わせる
names = ["たろう", "はなこ", "じろう"]
ages = [25, 30, 20]
for name, age in zip(names, ages):
    print(f"{name}さんは{age}歳です")

# 型変換
print(int("123"))           # 文字列 → 整数
print(float("3.14"))        # 文字列 → 少数
print(str(123))             # 数値 → 文字列
print(list("hello"))        # 文字列 → リスト

文字列処理

文字列を操作するためのメソッド群です。

text = "  Hello, World!  "

# 基本的な文字列操作
print(text.strip())             # 両端の空白を削除
print(text.lower())             # 小文字化
print(text.upper())             # 大文字化
print(text.replace("World", "Python"))  # 文字列置換

# 文字列の分割と結合
words = "りんご,バナナ,みかん".split(",")  # ["りんご", "バナナ", "みかん"]
joined = "-".join(words)                    # "りんご-バナナ-みかん"

# 部分一致検索など
print("Hello" in text)          # True(含まれているか)
print(text.startswith("  H"))   # True(先頭一致)
print(text.endswith("!  "))     # True(末尾一致)
print(text.find("World"))       # 見つかった位置(例: 9)

# フォーマット(f文字列)
name = "たろう"
age = 25
message = f"私は{name}です。{age}歳です。"
print(message)                  # "私はたろうです。25歳です。"

例外処理とファイル操作

例外処理(エラー対応)

プログラムでエラーが発生したときに、安全に処理を続けるための方法です。

# 基本的な例外処理
try:
    result = 10 / 0
except ZeroDivisionError:
    print("0で割ることはできません")
    result = None

# 複数の例外を処理
try:
    number = int(input("数字を入力してください: "))
    result = 100 / number
    print(f"結果: {result}")
except ValueError:
    print("整数を入力してください")
except ZeroDivisionError:
    print("0では割れません")
except Exception as e:
    print(f"予想外のエラー: {e}")

# finallyブロック(必ず実行される処理)
try:
    file = open("test.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("ファイルが見つかりません")
finally:
    print("終了処理を実行")
    try:
        file.close()
    except:
        pass

例外の送出(raise文)

独自にエラーを発生させたいときに使います。

def check_age(age):
    if age < 0:
        raise ValueError("年齢は0以上である必要があります")
    if age > 150:
        raise ValueError("年齢が大きすぎます")
    return age

try:
    check_age(-5)
except ValueError as e:
    print(f"エラー: {e}")

ファイルの読み書き

ファイルにデータを保存したり、読み込んだりします。

# 書き込み(上書き)
with open("example.txt", "w", encoding="utf-8") as file:
    file.write("こんにちは、世界!\n")
    file.write("Pythonは楽しいです。\n")

# 読み込み
with open("example.txt", "r", encoding="utf-8") as file:
    content = file.read()
    print(content)

# 1行ずつ読み込み
with open("example.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(f"行: {line.strip()}")

# 追記
with open("example.txt", "a", encoding="utf-8") as file:
    file.write("これは追記です。\n")

CSVファイルの扱い

表形式のデータ(表計算ソフトのような形式)を扱うための方法です。

import csv

# CSVファイルへの書き込み
data = [
    ["名前", "年齢", "職業"],
    ["たろう", 25, "エンジニア"],
    ["はなこ", 30, "デザイナー"]
]

with open("people.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(data)

# CSVファイルの読み込み
with open("people.csv", "r", encoding="utf-8") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# 辞書形式での読み込み
with open("people.csv", "r", encoding="utf-8") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(f"{row['名前']}さんは{row['年齢']}歳の{row['職業']}です")

JSONファイルの扱い

Web APIや設定ファイルでよく使われるデータ形式です。

import json

# Pythonの辞書をJSON文字列に変換
person = {
    "名前": "たろう",
    "年齢": 25,
    "趣味": ["読書", "料理"],
    "結婚": False
}

json_string = json.dumps(person, ensure_ascii=False, indent=2)
print(json_string)

# JSON文字列をPythonの辞書に変換
json_data = '{"名前": "はなこ", "年齢": 30}'
person_data = json.loads(json_data)
print(person_data["名前"])  # "はなこ"

# JSONファイルへの書き出し
with open("person.json", "w", encoding="utf-8") as file:
    json.dump(person, file, ensure_ascii=False, indent=2)

# JSONファイルの読み込み
with open("person.json", "r", encoding="utf-8") as file:
    loaded_person = json.load(file)
    print(loaded_person)

ディレクトリとパスの操作

ファイルやフォルダの存在確認や作成などの操作を行います。

import os
from pathlib import Path

# 現在のディレクトリを取得
current_dir = os.getcwd()
print(f"現在の位置: {current_dir}")

# ディレクトリ内のファイル一覧
files = os.listdir(".")
for file in files:
    print(f"ファイル: {file}")

# 新しいディレクトリを作成
os.makedirs("new_folder", exist_ok=True)

# パスの結合(OSに依存しない方法)
file_path = os.path.join("folder", "subfolder", "file.txt")

# Pathlibでのパス操作(推奨)
path = Path("folder") / "subfolder" / "file.txt"

# ファイルやフォルダの存在確認
if Path("example.txt").exists():
    print("ファイルが存在します")

if Path("folder").is_dir():
    print("ディレクトリです")

# ファイル情報の取得
file_path = Path("example.txt")
if file_path.exists():
    print(f"ファイルサイズ: {file_path.stat().st_size} バイト")
    print(f"更新日: {file_path.stat().st_mtime}")


実践的な使い方とデバッグのコツ

デバッグのテクニック

プログラムの不具合を見つけて修正するための方法です。

# print文でデバッグする
def calculate_average(numbers):
    print(f"デバッグ: 入力データ = {numbers}")
    total = sum(numbers)
    print(f"デバッグ: 合計 = {total}")
    count = len(numbers)
    print(f"デバッグ: 個数 = {count}")
    average = total / count
    print(f"デバッグ: 平均 = {average}")
    return average

# 実行
result = calculate_average([1, 2, 3, 4, 5])

# assert文によるチェック
def divide(a, b):
    assert b != 0, "ゼロで割ることはできません"
    return a / b

ロギング(loggingモジュール)

開発段階や本番環境での記録用ツールです。

import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

def process_data(data):
    logger.debug(f"データ処理開始: {data}")
    logger.info("処理中...")
    logger.warning("注意が必要です")
    logger.error("エラーが発生しました")

よく使うパターンとPython的な書き方(イディオム)

条件に合う要素を抽出する

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 偶数だけを取り出す
even_numbers = [n for n in numbers if n % 2 == 0]

defaultdict(デフォルト値付き辞書)

from collections import defaultdict

word_count = defaultdict(int)
for word in ["hello", "world", "hello"]:
    word_count[word] += 1

enumerate と zip の活用

names = ["たろう", "はなこ", "じろう"]
ages = [25, 30, 20]

# 番号付き辞書作成
person_dict = {i: name for i, name in enumerate(names)}

# 2つのリストを辞書に
name_age_dict = dict(zip(names, ages))

値の入れ替え(スワップ)

a, b = 10, 20
a, b = b, a  # 値を交換

条件の範囲チェック

age = 25
if 18 <= age <= 65:
    print("労働可能年齢")

any() と all() の活用

scores = [85, 90, 78, 92, 88]
has_excellent = any(score >= 90 for score in scores)   # 1つでも90点以上があればTrue
all_passed = all(score >= 60 for score in scores)      # 全員60点以上でTrue

続いて、「パフォーマンス向上のコツ」「便利な外部ライブラリの紹介」のセクションを漢字かな混じり文でお届けします。


パフォーマンス向上のコツ

プログラムを効率的に、速く動かすためのテクニックです。

実行時間の測定

import time

start_time = time.time()

# 実行したい処理
total = sum(range(1000000))

end_time = time.time()
print(f"実行時間: {end_time - start_time:.3f}秒")

リスト内包表記 vs 通常のfor文

# 高速(リスト内包表記)
squares_fast = [x * x for x in range(1000)]

# 低速(通常のfor文)
squares_slow = []
for x in range(1000):
    squares_slow.append(x * x)

setを使った高速検索

# リストでの検索(遅い)
large_list = list(range(10000))
start = time.time()
9999 in large_list
list_time = time.time() - start

# setでの検索(速い)
large_set = set(range(10000))
start = time.time()
9999 in large_set
set_time = time.time() - start

print(f"リスト検索時間: {list_time:.6f}秒")
print(f"セット検索時間: {set_time:.6f}秒")

便利な外部ライブラリの紹介

Pythonの可能性を広げてくれる有名なライブラリたちです。

requests(HTTPリクエスト)

# pip install requests
import requests

response = requests.get("https://api.github.com/users/octocat")
if response.status_code == 200:
    data = response.json()
    print(f"ユーザー名: {data['login']}")

pandas(データ分析)

# pip install pandas
import pandas as pd

df = pd.read_csv("data.csv")
print(df.head())        # 最初の5行
print(df.describe())    # 統計情報

# フィルタリング
filtered = df[df["age"] > 25]

matplotlib(グラフ描画)

# pip install matplotlib
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.xlabel("X軸")
plt.ylabel("Y軸")
plt.title("サンプルグラフ")
plt.show()

NumPy(高速数値計算)

# pip install numpy
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr * 2)  # [2, 4, 6, 8, 10]

# 2次元配列の行列演算
matrix = np.array([[1, 2], [3, 4]])
print(matrix.dot(matrix))


クラスとオブジェクト指向

コードを整理して再利用しやすくするための仕組みです。

クラスの基本定義と継承

# クラスの定義
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"こんにちは、{self.name}です"

    def have_birthday(self):
        self.age += 1
        print(f"誕生日おめでとう!{self.age}歳になりました")

# 使用例
person1 = Person("たろう", 25)
print(person1.greet())
person1.have_birthday()
# 継承を使ったクラス
class Student(Person):
    def __init__(self, name, age, school):
        super().__init__(name, age)
        self.school = school

    def study(self, subject):
        return f"{self.name}は{subject}を勉強しています"

student1 = Student("はなこ", 20, "東京大学")
print(student1.greet())
print(student1.study("Python"))

特別メソッド(ダンダーメソッド)

class Calculator:
    def __init__(self, value=0):
        self.value = value

    def __str__(self):
        return f"Calculator({self.value})"

    def __add__(self, other):
        if isinstance(other, Calculator):
            return Calculator(self.value + other.value)
        return Calculator(self.value + other)

    def __len__(self):
        return len(str(self.value))

calc1 = Calculator(10)
calc2 = Calculator(5)
result = calc1 + calc2
print(result)  # Calculator(15)

モジュールとパッケージの管理

コードをファイル単位で分割し、再利用しやすくします。

# mymodule.py の中身
def hello(name):
    return f"Hello, {name}!"

def add_numbers(a, b):
    return a + b

PI = 3.14159

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return PI * self.radius ** 2
# 呼び出し側のファイル
import mymodule

print(mymodule.hello("たろう"))
print(mymodule.add_numbers(5, 3))

# 特定の関数のみインポート
from mymodule import hello, Circle

circle = Circle(5)
print(f"円の面積: {circle.area()}")

# モジュールに別名をつける
import mymodule as mm
print(mm.PI)

まとめ

Pythonチートシートは、学習中の確認ツールとしても、開発中の参考資料としても非常に便利です。

覚えておきたいポイント

  • 基本文法:変数、条件分岐、繰り返し
  • データ構造:リスト、辞書、セット、タプル
  • 関数とクラス:再利用性と構造化
  • ライブラリ:外部ツールを活用
  • ファイル操作・例外処理:実用的な場面で重要

コメント

タイトルとURLをコピーしました