数値操作
絶対値の取得
print(abs(-8)) # 出力: 8
進数変換
print(bin(12)) # 2進数: 0b1100
print(oct(15)) # 8進数: 0o17
print(hex(20)) # 16進数: 0x14
整数と文字変換
print(chr(66)) # 'B'
print(ord('Z')) # 90
真偽値チェック
print(all([True, False, True])) # False
print(any([0, None, 1])) # True
print(bool([])) # False
複素数生成
comp = complex(2, 3)
print(comp) # (2+3j)
商と剰余
result = divmod(15, 4)
print(result) # (3, 3)
型変換
print(float(7)) # 7.0
print(int('24', 8)) # 20
累乗計算
print(pow(4, 3, 5)) # 64 % 5 = 4
数値丸め
print(round(12.3456, 2)) # 12.35
連続比較
value = 5
print(3 < value <= 6) # True
文字列処理
バイト変換
data = "python".encode('utf-8')
print(data) # b'python'
文字列変換
num_str = str(50)
print(num_str) # '50'
動的コード実行
exec_code = compile('print("Hello")', '', 'exec')
exec(exec_code)
式評価
calc = eval('5 * 3 + 2')
print(calc) # 17
書式設定
text = "名前: {0}, 年齢: {1}".format("太郎", 25)
print(text)
関数操作
ソート処理
nums = [5, 1, 9]
print(sorted(nums, reverse=True)) # [9, 5, 1]
合計計算
values = [3, 7, 2]
print(sum(values, 10)) # 22
変数スコープ
def outer():
count = 0
def inner():
nonlocal count
count += 1
inner()
print(count)
outer() # 1
値交換
def swap_values(x, y):
return y, x
print(swap_values(3, 7)) # (7, 3)
逆順生成
reverse_seq = list(range(10, -1, -2))
print(reverse_seq) # [10, 8, 6, 4, 2, 0]
データ構造
辞書生成
dict1 = dict(key1='value1', key2=100)
dict2 = dict([('a', 1), ('b', 2)])
print(dict1, dict2)
固定集合
immutable_set = frozenset([4, 4, 2, 8])
print(immutable_set) # frozenset({8, 2, 4})
スライス操作
seq = [0, 1, 2, 3, 4]
slicer = slice(1, 4, 2)
print(seq[slicer]) # [1, 3]
クラスとオブジェクト
呼び出し可能チェック
class CallableClass:
def __call__(self):
print("Called")
obj = CallableClass()
print(callable(obj)) # True
属性操作
class Sample:
def __init__(self):
self.attr = 10
obj = Sample()
delattr(obj, 'attr')
print(hasattr(obj, 'attr')) # False
プロパティ設定
class PropertyDemo:
def __init__(self):
self._x = None
@property
def data(self):
return self._x
@data.setter
def data(self, val):
self._x = val
instance = PropertyDemo()
instance.data = 15
print(instance.data) # 15
ユーティリティ
列挙処理
for idx, item in enumerate(['A', 'B', 'C'], 1):
print(f"{idx}: {item}")
フィルタリング
filtered = filter(lambda n: n % 2 == 0, [1, 2, 3, 4])
print(list(filtered)) # [2, 4]
イテレータ生成
iter_obj = iter([10, 20, 30])
print(next(iter_obj)) # 10
逆順イテレーション
rev_iter = reversed("Python")
print(''.join(rev_iter)) # nohtyP
データ圧縮
zipped = zip([1, 2], ['a', 'b'])
print(list(zipped)) # [(1, 'a'), (2, 'b')]
JSONシリアライズ
import json
data = {"name": "太郎", "age": 30}
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)