Python では変数を利用するために最初に定義をする必要があります。ここでは変数を定義する方法や、変数名の付け方などについて解説します。
・変数の定義
Python では変数を使用する時に事前に使用する変数を宣言したり、変数で扱うデータ型を指定する必要はありません。ただし定義されていない変数の値を参照しようとするとエラーが発生します。
#事前に変数を定義していない場合、エラーが発生
print(test)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined
#以下は定義した後に実行
test = "テストです"
print(test)
テストです
変数に代入できる値は、数値・文字列・その他のオブジェクトなどです。
num = 100
chr = "テストだよ"
testList = ["test1","test2","test3"]
testDic = {"one":"1","two":"2","three":"3"}
print(num,chr,testList,testDic["one"])
100 テストだよ ['test1', 'test2', 'test3'] 1
・変数名の付け方
変数名を定義するにあたって、以下ルールを守る必要があります。
・使用できる文字は a ~ z 、 A ~ Z 、 0 ~ 9 、アンダーバー(_)、漢字など
・一文字目に数値(0~9)は使用できない
・一文字目にアンダーバーは使用できるがお勧めしない
・大文字と小文字は区別される
・予約語は使用できない
予約語一覧を以下に示します。
False | await | else | import | pass |
None | break | except | in | raise |
True | class | finally | is | return |
and | continue | for | lambda | try |
as | def | from | nonlocal | while |
assert | del | global | not | with |
async | elif | if | or | yield |
これらを使って変数を定義すると、エラーとなります。
False = 1000
File "<stdin>", line 1
SyntaxError: cannot assign to False
・定義した変数はいつでも変更できる
以下の通り、変数はいくらでも変更することができます。
test = "test ippon"
print(test)
test ippon
test = 1000
print(test)
1000
test = ""
print(test)
・変数に変数を定義することができる
変数に対して、変数を定義することができます。以下をご覧ください。
test1 = 1000
test2 = test1
print(test2)
1000
複雑な計算をさせたいときなど、必要になることがあります。
注意点は「test1」の値が変わった場合でも「test2」の値は変わらないということです。
test1 = 1000
test2 = test1
print(test2)
1000
test1 = 2000
print(test2)
1000