0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Python】変数と型

Last updated at Posted at 2024-06-06

変数

Pythonでは変数を使ってデータを格納することができます。変数には以下の特徴があります。

変数名の命名規則

  • 変数名は文字(アルファベットまたはアンダースコア_)で始まる必要があります
  • 変数名には文字、数字、アンダースコアを含めることができます
  • 大文字と小文字は区別されます(name, Nameは別の変数)
  • 予約語(print, if, forなど)は変数名に使えません

代入

x = 5       # 整数値を代入
y = 3.14    # 浮動小数点数を代入
name = "John" # 文字列を代入
is_student = True # 真理値(Boolean)を代入

  • Pythonは動的型付け言語なので、変数の型は値によって決まります
  • 同じ変数に異なる型のデータを代入することができます

スコープ

  • 変数のスコープは、その変数が定義された場所によって決まります
  • 関数の外で定義された変数はグローバルスコープ
  • 関数の中で定義された変数はローカルスコープ
x = 10 # グローバル変数

def foo():
    y = 5 # ローカル変数
    print(x) # グローバル変数xは参照できる
    print(y) 

foo() # xの値10、yの値5が出力される
print(y) # エラー、yはローカル変数でグローバルスコープからはアクセスできない

変数は任意の値を格納でき、コードの実行過程で値を変更することもできます。変数を上手く活用することで、プログラムのデータの流れをコントロールできます。

Pythonは動的型付け言語なので、変数に値を代入する際に型を明示する必要はありません。主な型は以下の通りです。

数値型

  • 整数型(int): x = 5
  • 浮動小数点数型(float): y = 3.14
  • 複素数型(complex): z = 2 + 3j

ブール型

  • 真理値(True/False): bool_value = True

シーケンス型

  • 文字列型(str): s = "Hello"
  • リスト型(list): lst = [1, 2, 3]
  • タプル型(tuple): tup = (4, 5, 6)

マッピング型

  • 辞書型(dict): d = {"apple": 2, "banana": 3}

セット型

  • セット(set): st = {1, 2, 3}

型に合わせた演算や操作ができます。例えば:

x = 5
y = 2.5
z = x + y     # 7.5 (数値の加算)

s1 = "Hello"
s2 = "World"
s3 = s1 + s2  # "HelloWorld" (文字列の連結)

lst = [1, 2, 3]
lst.append(4) # lst は [1, 2, 3, 4] になる (リストへの値の追加)

データ型を取得するには type() 関数を使います。

print(type(5))     # <class 'int'>
print(type(3.14))  # <class 'float'>
print(type("Hi"))  # <class 'str'>

型変換もできます。int()float()str()などの関数で明示的に別の型に変換できます。

Pythonでは動的に型が決まるので、プログラマは型について気をつける必要がありますが、柔軟な型システムがPythonの利点の一つでもあります。

参考) 東京工業大学情報理工学院 Python早見表

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?