数値
文字列と並んで大切な数値を説明します。
四則演算(加算・減算・乗算・除算)は下記の通りです。
# -*- coding: utf-8 -*- test_integer = 100 print test_integer + 10 # 加算(足し算) print test_integer - 10 # 減算(引き算) print test_integer * 10 # 乗算(掛け算) print test_integer / 10 # 除算(割り算)
--実行結果--
110 90 1000 10
数値(整数)への変換は「int」を使用します。
# -*- coding: utf-8 -*- test_str = '100' print int(test_str) + 100
--実行結果--
200
プログラミング言語では、基本的に小数点を含まない数値(int)と小数点を含む数値(float)が区別され、小数点を含む数値を浮動小数点数といいます。浮動小数点数への変換は「float」を使用します。
# -*- coding: utf-8 -*- test_str = '100.5' print float(test_str) + 100
--実行結果--
200.5
また「0.5」のように整数部がゼロの場合はそれを省略して記述することができます。
# -*- coding: utf-8 -*- test_float = .5 print test_float
--実行結果--
0.5
複素数を表すcomplexは、数値へ「j」や「J」を付与することで虚数になります。次の例は実数が「100」、虚数が「5」の複素数です。
# -*- coding: utf-8 -*- test_complex = 100 + 5j print test_complex print test_complex.real print test_complex.imag
--実行結果--
(100+5j) 100.0 5.0
少なめですが数値は以上となります。次は日付・時間!
▶基礎編:日付・時間
