Python 数字
- Previous Page Python Datatypen
- Next Page Python Casting
Python 数字
Python 中有三种数字类型:
- int
- float
- complex
为变量赋值时,将创建数值类型的变量:
Example
x = 10 # int y = 6.3 # float z = 2j # complex
如需验证 Python 中任何对象的类型,请使用 type()
函数:
Example
print(type(x)) print(type(y)) print(type(z))
Int
Int 或整数是完整的数字,正数或负数,没有小数,长度不限。
Example
整数:
x = 10 y = 37216654545182186317 z = -465167846 print(type(x)) print(type(y)) print(type(z))
Float
浮动或“浮点数”是包含小数的正数或负数。
Example
浮点:
x = 3.50 y = 2.0 z = -63.78 print(type(x)) print(type(y)) print(type(z))
浮点数也可以是带有“e”的科学数字,表示 10 的幂。
Example
浮点:
x = 27e4 y = 15E2 z = -49.8e100 print(type(x)) print(type(y)) print(type(z))
复数
复数用 "j" 作为虚部编写:
Example
复数:
x = 2+3j y = 7j z = -7j print(type(x)) print(type(y)) print(type(z))
Type Conversion
You can use int()
,float()
and complex()
Method to convert from one type to another:
Example
Convert from one type to another:
x = 10 # int y = 6.3 # float z = 1j # complex # Convert an integer to a float a = float(x) # Convert a float to an integer b = int(y) # Convert an integer to a complex number: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c))
Note:You cannot convert a plural to another number type.
random numbers
Python does not have random()
A function to create random numbers, but Python has a function called random
The built-in module, which can be used to generate random numbers:
Example
Import the random module and display a random number between 1 and 9:
import random print(random.randrange(1,10))
In Random Module Reference Manual In this section, you will learn more about the Random module.
- Previous Page Python Datatypen
- Next Page Python Casting