Python番号
Python番号
Pythonには3つの数値型があります。
int
float
complex
数値タイプの変数は、それらに値を割り当てると作成されます。
例
x = 1
# int
y = 2.8 # float
z = 1j # complex
Pythonでオブジェクトのタイプを確認するには、次のtype()
関数を使用します。
例
print(type(x))
print(type(y))
print(type(z))
Int
Intまたは整数は、長さが無制限の、小数を含まない正または負の整数です。
例
整数:
x = 1
y = 35656222554887711
z =
-3255522
print(type(x))
print(type(y))
print(type(z))
浮く
浮動小数点数、または「浮動小数点数」は、1つ以上の小数点以下を含む正または負の数値です。
例
ポンツーン:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
フロートは、10の累乗を示す「e」が付いた科学的数値にすることもできます。
例
ポンツーン:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
複雑
複素数は、虚数部として「j」を使用して記述されます。
例
複雑:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
型変換
、、、およびメソッドを使用してint()
、
あるタイプから別のタイプに変換できます。float()
complex()
例
あるタイプから別のタイプに変換します。
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
注:複素数を別の数値型に変換することはできません。
乱数
random()
Pythonには乱数を作成する関数
はありませんが、 Pythonには、乱数random
を作成するために使用できると呼ばれる組み込みモジュールがあります。
例
ランダムモジュールをインポートし、1から9までの乱数を表示します。
import random
print(random.randrange(1, 10))
ランダムモジュールリファレンスでは、ランダムモジュールについて詳しく学びます。