Python 数字

Python 数字

Python 中有三种数字类型:

  • int
  • float
  • complex

为变量赋值时,将创建数值类型的变量:

Instance

x = 10   # int
y = 6.3  # float
z = 2j   # complex

如需验证 Python 中任何对象的类型,请使用 type() 函数:

Instance

print(type(x))
print(type(y))
print(type(z))

Run Instance

Int

Int 或整数是完整的数字,正数或负数,没有小数,长度不限。

Instance

整数:

x = 10
y = 37216654545182186317
z = -465167846
print(type(x))
print(type(y))
print(type(z))

Run Instance

Float

浮动或“浮点数”是包含小数的正数或负数。

Instance

浮点:

x = 3.50
y = 2.0
z = -63.78
print(type(x))
print(type(y))
print(type(z))

Run Instance

浮点数也可以是带有“e”的科学数字,表示 10 的幂。

Instance

浮点:

x = 27e4
y = 15E2
z = -49.8e100
print(type(x))
print(type(y))
print(type(z))

Run Instance

复数

复数用 "j" 作为虚部编写:

Instance

复数:

x = 2+3j
y = 7j
z = -7j
print(type(x))
print(type(y))
print(type(z))

Run Instance

Type Conversion

Maaari ninyong gamitin ang int()float() at complex() Ang pamamaraan upang mag-convert ng isang uri ng tipo sa ibang uri ng tipo:

Instance

Pag-convert ng isang uri ng tipo sa ibang uri ng tipo:

x = 10 # integer
y = 6.3 # float
z = 1j # complex
# Pag-convert ng integer sa floating-point number
a = float(x)
# Pag-convert ng floating-point number sa integer
b = int(y)
# Pag-convert ng integer sa complex number:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))

Run Instance

Komentaryo:Hindi kayang palitan ang pambansang numero ng ibang uri ng numero.

Random Number

Wala sa Python ang random() Ang function upang gumawa ng random number, ngunit mayroon sa Python ang pangalan na random Ang mga nakalagay na module, na maaring gamitin para sa paglikha ng random number:

Instance

I-import ang random module at ipakita ang random number sa pagitan ng 1 hanggang 9:

import random
print(random.randrange(1,10))

Run Instance

Sa Random Module Reference Manual Sa, malalaman ninyo ang mas maraming impormasyon tungkol sa Random Module.