Pythonでは、変数のデータ型を確認するためにtype()
関数を使用します。この関数は、引数として渡されたオブジェクトのデータ型を返します。
以下に、Pythonでデータ型を表示する基本的な方法を示します。
x = 5
print(type(x))
このコードは、変数x
のデータ型を表示します。
また、Pythonではすべてがオブジェクトであるため、type()
関数を使用して変数に格納されている値のデータ型を表示すると、そのオブジェクトのクラス型が返されます。
例えば、以下のように様々なデータ型を持つ変数を宣言し、それぞれのデータ型を表示することができます。
name = "freeCodeCamp"
score = 99.99
lessons = ["RWD", "JavaScript", "Databases", "Python"]
person = {"firstName": "John", "lastName": "Doe", "age": 28}
langs = ("Python", "JavaScript", "Golang")
basics = {"HTML", "CSS", "JavaScript"}
print("The variable, name is of type:", type(name))
print("The variable, score is of type:", type(score))
print("The variable, lessons is of type:", type(lessons))
print("The variable, person is of type:", type(person))
print("The variable, langs is of type:", type(langs))
print("The variable, basics is of type:", type(basics))
このコードを実行すると、以下のような出力が得られます。
The variable, name is of type: <class 'str'>
The variable, score is of type: <class 'float'>
The variable, lessons is of type: <class 'list'>
The variable, person is of type: <class 'dict'>
The variable, langs is of type: <class 'tuple'>
The variable, basics is of type: <class 'set'>
これらの情報を利用して、Pythonでのデータ型の取得と表示方法について理解を深めることができます。また、Pythonでは変数はデータ型で宣言されないため、type()
関数は変数のデータ型を確認するために組み込まれています。これにより、デバッグ時にも役立ちます。.