Python: データ型, input 関数, type 関数, format 関数

Python 独習メモ


データ型

int    整数    123, -100

float    小数    3,14, -0.7

str    文字列    "Hello", "ハンバーグ"

bool    真偽値    True, False


input 関数

変数名 = input(文字列)


x = input("円周率は?")

print(x)

実行結果

円周率は?3.14

3.14


type 関数

格納されている値のデータ型を調べる

type(変数名)


x = 10

print(type(x))

実行結果

<class 'int'>


データ型の変換

int 関数    int(x)    変数 x の値を int 型に変換

float 関数    float(x)    変数 x の値を float 型に変換

str 関数    str(x)    変数 x の値を str 型に変換

bool 関数    bool(x)     変数 x の値を bool 型に変換


x = 3.14

y = int(x)

print(y)

print(type(y))

z = str(x)

print(z)

print(type(z))

print(z * 2)

実行結果

3

<class 'int'>

3.14

<class 'str'>

3.143.14


format 関数

"{} を含む文字列".format(埋め込む値1, 埋め込む値2, …)


name = input("名前?")

age = input("年齢?")

height = input("身長?")

print("私の名前は{}で、年齢は{}歳で、身長は{}cmです".format(name, age, height))

実行結果

名前?吉田

年齢?17

身長?162

私の名前は吉田で、年齢は17歳で、身長は162cmです


上記は f-string を使って簡潔に書くことが可能。


name = input("名前?")

age = input("年齢?")

height = input("身長?")

print(f"私の名前は{name}で、年齢は{age}歳で、身長は{height}cmです")

実行結果

名前?有友

年齢?16

身長?160

私の名前は有友で、年齢は16歳で、身長は160cmです


Pythonの文字列フォーマット(formatメソッドの使い方)


もどる

このブログの人気の投稿

日本のオーディオメーカー一覧

「ミュージック」アプリでアルバムアートが削除できない

メディアサーバーの Plex, Emby, Jellyfin を試す

増え続ける iTunes のコンピレーションを減らす(Windows)

電力会社と音質