1
1

More than 3 years have passed since last update.

python:型指定して変数を定義するときに:を使用する

Last updated at Posted at 2021-09-14

pythonで型指定した変数を定義することができます。

basic.py
>>> val_initial : int = 2

この型指定された変数の値の変更の仕方には癖があります。

sample1.py

>>> thickness: int = 2
>>> print(thickness)
2
>>> print(type(thickness))
<class 'int'>
>>> name: str = 'hello'
>>> print(type(name))
<class 'str'>

下記のように数字を入れた変数xをint型指定されたvalに代入したときに

その変数xの値を変更したときに、valは自動では書き換わりません。

sample2.py
>>> x = 2      
>>> val:int = x
>>> print(val)
2
>>> x = 12
>>> print(val)
2
>>> val:int = x
>>> print(val)
12

型指定の変数を宣言できますが、
そこに型が決まってない変数を代入することはできません。

sample3.py
>>> val2:int
>>>
>>> val3:int = y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
1
1
2

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
1
1