****
Pythonにおいて、int()、float()、complex()はそれぞれ整数型、浮動小数点型、複素数型に変換するための組み込み関数です。この記事では、これらの関数の基本的な使い方から注意点までをコードを交えて詳しく説明します。
int() 関数 - 整数型への変換
int()関数は、与えられた値を整数型に変換します。基本的な使い方は以下の通りです。
# 文字列を整数に変換 num_str = "123" int_value = int(num_str) print(f"Converted integer: {int_value}") # 浮動小数点数を整数に変換 float_value = 456.789 int_from_float = int(float_value) print(f"Converted integer from float: {int_from_float}")
float() 関数 - 浮動小数点型への変換
float()関数は、与えられた値を浮動小数点型に変換します。以下は基本的な使用例です。
# 整数を浮動小数点数に変換 num_int = 789 float_value = float(num_int) print(f"Converted float: {float_value}") # 文字列を浮動小数点数に変換 num_str = "456.789" float_value_str = float(num_str) print(f"Converted float from string: {float_value_str}")
complex() 関数 - 複素数型への変換
complex()関数は、与えられた値を複素数型に変換します。実数部と虚数部を指定します。
# 実数と虚数を指定して複素数を生成 real_part = 2.5 imag_part = -1.3 complex_number = complex(real_part, imag_part) print(f"Generated complex number: {complex_number}") # 文字列を複素数に変換 complex_str = "3+4j" complex_from_str = complex(complex_str) print(f"Converted complex number from string: {complex_from_str}")
注意点とまとめ
int()やfloat()、complex()関数は、数値型への変換に利用されます。- 文字列からの変換や、異なる数値型同士の変換が可能ですが、注意が必要です。
- 複素数型は実数部と虚数部を指定して生成します。
これらの関数は、数値型の変換や生成において非常に便利であり、Pythonの柔軟性を高める上で重要な役割を果たしています。数値計算やデータ処理において、適切な型への変換を行いながらコーディングすることが重要です。
これで、int()、float()、complex()関数の基本的な使い方について理解できたかと思います。何か質問があればお気軽にどうぞ!