基本構文
Python
変数・型・制御フロー・関数
変数と型
動的型付けと型ヒント
# 型推論(型注釈不要)
name = 'Alice'
age = 30
price = 3.14
active = True
nothing = None
# 型ヒント(Python 3.9+)
from typing import Optional
def greet(name: str, age: int = 0) -> str:
return f'こんにちは、{name}!{age}歳ですね。'
# 複合型ヒント
def process(
items: list[str],
config: dict[str, int],
callback: Optional[callable] = None,
) -> tuple[bool, str]:
return True, 'ok'
# 型の確認
type(42) # <class 'int'>
isinstance(42, int) # True
isinstance(42, (int, float)) # True
# 型変換
int('42') # 42
float('3.14') # 3.14
str(42) # '42'
bool(0) # False
list('abc') # ['a', 'b', 'c']
tuple([1,2,3]) # (1, 2, 3)
set([1,1,2]) # {1, 2}文字列操作
f-string・メソッド・スライス
# f-string(推奨)
name, price = 'Alice', 3.14159
f'こんにちは、{name}!'
f'価格: {price:.2f}円' # 書式指定
f'値: {1 + 2}' # 式の評価
f'{name!r}' # repr()
f'{name:>10}' # 右寄せ10文字
f'{1000000:,}' # 1,000,000
# 主なメソッド
s = ' Hello, World! '
s.strip() # 'Hello, World!'
s.lower() # ' hello, world! '
s.upper() # ' HELLO, WORLD! '
s.replace('World', 'Python') # ' Hello, Python! '
s.split(', ') # [' Hello', 'World! ']
', '.join(['a','b','c']) # 'a, b, c'
s.startswith(' H') # True
s.endswith(' ') # True
'abc'.center(7, '-') # '--abc--'
# スライス
s = 'Hello, World!'
s[0] # 'H'
s[-1] # '!'
s[7:12] # 'World'
s[:5] # 'Hello'
s[::2] # 'Hlo ol!'
s[::-1] # '!dlroW ,olleH' ← 逆順
# 文字列チェック
'abc'.isalpha() # True
'123'.isdigit() # True
'abc123'.isalnum()# True
' '.isspace() # True制御フロー
if・for・while・match・例外処理
# if / elif / else
x = 10
if x > 0:
print('正')
elif x == 0:
print('ゼロ')
else:
print('負')
# 三項演算子
result = '偶数' if x % 2 == 0 else '奇数'
# for ループ
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(2, 10, 2): # 2,4,6,8
print(i)
for i, val in enumerate(['a','b','c'], start=1):
print(i, val) # 1 a, 2 b, 3 c
for a, b in zip([1,2,3], ['x','y','z']):
print(a, b) # 1 x, 2 y, 3 z
# match / case(Python 3.10+)
status = 200
match status:
case 200: print('OK')
case 404: print('Not Found')
case 400 | 422: print('Bad Request')
case _: print('その他')
# 例外処理
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f'エラー: {e}')
except (TypeError, ValueError) as e:
print(f'型エラー: {e}')
else:
print('成功') # 例外がなかった場合
finally:
print('常に実行') # 常に実行
# 例外の再送出
try:
risky()
except Exception as e:
log(e)
raise # 同じ例外を再送出関数
引数・デコレーター・型ヒント
# 基本
def add(a: int, b: int = 0) -> int:
return a + b
# *args(可変長位置引数)
def sum_all(*nums: int) -> int:
return sum(nums)
sum_all(1, 2, 3, 4) # 10
# **kwargs(可変長キーワード引数)
def create_user(**kwargs: str) -> dict:
return kwargs
create_user(name='Alice', role='admin')
# キーワード専用引数(* の後)
def connect(host: str, *, port: int = 3000, timeout: int = 30):
pass
connect('localhost', port=8080) # port はキーワード必須
# デコレーター
import functools, time
def timer(func):
@functools.wraps(func) # func のメタデータを保持
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f'{func.__name__}: {time.perf_counter() - start:.3f}s')
return result
return wrapper
@timer
def slow_function():
time.sleep(0.1)
# デコレーターに引数を渡す
def retry(times: int = 3):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for i in range(times):
try:
return func(*args, **kwargs)
except Exception:
if i == times - 1: raise
return wrapper
return decorator
@retry(times=5)
def flaky_api(): ...