基本構文
変数と型
name = "Alice"
age = 25
price = 19.99
is_active = True
type(name)
int("42")
str(42)
float("3.14")
bool(1)
list("abc")
文字列
name = "Alice"
f"Hello, {name}!"
"Hello, {}!".format(name)
"Hello, %s!" % name
s = "hello world"
s.upper()
s.lower()
s.capitalize()
s.title()
s.strip()
s.split()
s.replace("l", "L")
s.startswith("h")
s.endswith("d")
"o" in s
s[0]
s[-1]
s[0:5]
s[::2]
s[::-1]
リスト
items = [1, 2, 3, 4, 5]
items = list(range(1, 6))
items.append(6)
items.insert(0, 0)
items.extend([7, 8])
items.pop()
items.pop(0)
items.remove(3)
items.index(2)
items.count(2)
items.sort()
items.reverse()
sorted(items)
len(items)
items[1:3]
items[::2]
items[-3:]
squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
matrix = [[i*j for j in range(3)] for i in range(3)]
辞書
user = {"name": "Alice", "age": 25}
user = dict(name="Alice", age=25)
user["email"] = "alice@example.com"
user.get("name")
user.get("phone", "N/A")
user.keys()
user.values()
user.items()
user.pop("age")
user.update({"city": "Tokyo"})
"name" in user
squares = {x: x**2 for x in range(5)}
セット
s = {1, 2, 3}
s = set([1, 2, 2, 3])
s.add(4)
s.remove(1)
s.discard(1)
s.pop()
a = {1, 2, 3}
b = {2, 3, 4}
a | b
a & b
a - b
a ^ b
制御構文
条件分岐
if x > 0:
print("positive")
elif x < 0:
print("negative")
else:
print("zero")
result = "even" if x % 2 == 0 else "odd"
match status:
case "pending":
print("保留中")
case "approved":
print("承認済み")
case _:
print("不明")
ループ
for i in range(5):
print(i)
for item in items:
print(item)
for i, item in enumerate(items):
print(i, item)
for key, value in user.items():
print(key, value)
while condition:
if should_break:
break
if should_skip:
continue
関数
def greet(name: str) -> str:
return f"Hello, {name}!"
def greet(name: str = "World") -> str:
return f"Hello, {name}!"
def sum_all(*args):
return sum(args)
def create_user(**kwargs):
return kwargs
square = lambda x: x ** 2
sorted(items, key=lambda x: x["name"])
クラス
from dataclasses import dataclass
from typing import Optional
class User:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def greet(self) -> str:
return f"Hello, {self.name}!"
@dataclass
class User:
name: str
age: int
email: Optional[str] = None
def greet(self) -> str:
return f"Hello, {self.name}!"
ファイル操作
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, World!")
import json
with open("data.json", "r") as f:
data = json.load(f)
with open("data.json", "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
例外処理
try:
result = 10 / 0
except ZeroDivisionError:
print("ゼロ除算エラー")
except Exception as e:
print(f"エラー: {e}")
else:
print("成功")
finally:
print("常に実行")
raise ValueError("無効な値です")
よく使うモジュール
from pathlib import Path
path = Path("dir/file.txt")
path.exists()
path.is_file()
path.read_text()
path.write_text("content")
path.parent
path.stem
from datetime import datetime, timedelta
now = datetime.now()
now.strftime("%Y-%m-%d %H:%M:%S")
datetime.strptime("2025-01-10", "%Y-%m-%d")
now + timedelta(days=7)
import re
re.match(r"\d+", "123abc")
re.search(r"\d+", "abc123")
re.findall(r"\d+", "a1b2c3")
re.sub(r"\d+", "X", "a1b2")
import requests
res = requests.get("https://api.example.com/data")
res.json()
requests.post(url, json={"key": "value"})
関連記事
← 一覧に戻る